Hi I have a table with comma delimited columns and I need to convert the comma delimited values to new rows. for exmaple the given table is
Name Start End
A 1,2,3 4,5,6
B 1,2 4,5
C 1,2,3,4 6,7,8,9
I need to convert it like
Name Start End
A 1 4
A 2 5
A 3 6
B 1 4
B 2 5
C 1 6
C 2 7
C 3 8
C 4 9
I can do that using VB script but I need to solve it using R Can anyone solve this?
Here's another, just for fun. Take
d
as the original data.The
separate_rows()
function intidyr
is the boss for observations with multiple delimited values...You might have asked this question on SO as there is no issue dealing with statistics :)
Anyway, I made up a quite complicated and ugly solution which might work for you:
Which looks like in R like:
Data transformation with the help of
strsplit
calls:Naming the new data frame:
Which looks like:
Here's an approach that should work for you. I'm assuming that your three input vectors are in different objects. We are going to create a list of those inputs and write a function that process each object and returns them in the form of a
data.frame
with plyr.The things to take note of here are the splitting of the character vector into it's component parts, then using
as.numeric
to convert the numbers from the character form when they were split. Since R fills matrices by column, we define a 2 column matrix and let R fill the values for us. We then retrieve the Name column and put it all together in adata.frame
.plyr
is nice enough to process the list and convert it into adata.frame
for us automatically.And the output: