Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reshape dataframe based on a string split in one column in R

I have the following data structure

ID  Type  Values
1   A     5; 7; 8
2   A     6
3   B     2; 3

and I would like to reshape it to the following using R:

ID  Type  Values
1   A     5
1   A     7
1   A     8
2   A     6
3   B     2
3   B     3

I've been trying to work out how to do it with plyr but without any success. What is the best way to do this?

like image 263
yoda230 Avatar asked Oct 01 '12 13:10

yoda230


People also ask

How do I split a string in a column in R?

To split a column into multiple columns in the R Language, We use the str_split_fixed() function of the stringr package library. The str_split_fixed() function splits up a string into a fixed number of pieces.

How do I separate delimiter in R?

Use str_split to Split String by Delimiter in R Alternatively, the str_split function can also be utilized to split string by delimiter. str_split is part of the stringr package. It almost works in the same way as strsplit does, except that str_split also takes regular expressions as the pattern.


1 Answers

Since you asked for a plyr solution, here you go:

ddply(df, .(Type), function(foo) {
    values <- unlist(strsplit(c(foo$Values), ";"))
    data.frame(Type = rep(unique(foo$Type), length(values)), Values = values)
    })
like image 120
Maiasaura Avatar answered Oct 17 '22 11:10

Maiasaura