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?
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.
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.
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With