Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use strplit in tidyverse dataframe

I have a data frame in R with several columns. In one column, I want to use strsplit to extract part of the string and put it into another column. I have a data frame with a column called IDName, the IDName has strings in this format:

1-John
2-Tom

and I want to split the string and put ID in its own column and name in its own column

InputDF%>% mutate(ID=strsplit(IDName, "-"))-> OutputDF

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this doesn’t put ID in the ID column, but it is a list, how can I extract ID and Name using the above code?

I tried this:

  InputDF%>%  mutate(ID=strsplit(IDName, "-")[[0]])-> OutputDF

But I am getting errors.

What is the best way to do this?

>Solution :

We could use separate function from tidyr package:

library(dplyr)
library(tidyr)

df %>% 
  separate(x, c("ID", "name"), sep = '-')

output:

  ID    name 
  <chr> <chr>
1 1     John 
2 2     Tom  

data:

df <- tribble(
  ~x,
"1-John",
"2-Tom")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading