Search code examples
rtidyversestrsplit

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

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")