0 votes
1 view
in R Programming by (5.3k points)

I'd like to take data of the form

before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))

  attr          type

1    1   foo_and_bar

2   30 foo_and_bar_2

3    4   foo_and_bar

4    6 foo_and_bar_2

and use split() on the column "type" from above to get something like this:

  attr type_1 type_2

1    1    foo    bar

2   30    foo  bar_2

3    4    foo    bar

4    6    foo  bar_2

I came up with something unbelievably complex involving some form of application that worked, but I've since misplaced that. It seemed far too complicated to be the best way. I can use strsplit as below, but then unclear how to get that back into 2 columns in the data frame.

> strsplit(as.character(before$type),'_and_')


[1] "foo" "bar"


[1] "foo"   "bar_2"


[1] "foo" "bar"


[1] "foo"   "bar_2"

Thanks for any pointers. I've not quite broken R lists just yet.

1 Answer

0 votes
by (25.3k points)
edited by

To split a string column from a data frame into multiple columns, you can use the separate function from the tidyr package as follows:



before %>%

  separate(type, c("foo", "bar"), "_and_")


   attr foo   bar

1    1 foo   bar

2   30 foo bar_2

3    4 foo   bar

4    6 foo bar_2

Welcome to Intellipaat Community. Get your technical queries answered by top developers !