0

I'm trying to figure out how to do this but not sure how. For example, if I have...

ID  Name  Type                 Other

1   Andy  Test1; Test2; Test3  Other1; Other2; Other3

I'd like for R to return...

ID  Name  Type   Other

1   Andy  Test1  Other1
1   Andy  Test2  Other2
1   Andy  Test3  Other3

Is there any way to partition the data to get that?

cpd1
  • 777
  • 11
  • 31
  • 1
    See here: http://stackoverflow.com/questions/13773770/split-comma-separated-column-into-separate-rows, along with all the linked questions on that previous question. – thelatemail Jan 14 '15 at 01:14
  • @thelatemail, but that answer doesn't include `library(splitstackshape); cSplit(mydf, c("Type", "Other"), ";", "long")`! :-) – A5C1D2H2I1M1N2O1R2T1 Jan 14 '15 at 02:15
  • 1
    @AnandaMahto - a tragic oversight no doubt! – thelatemail Jan 14 '15 at 02:28
  • Thank you! I will give this a shot in a little bit and report back – cpd1 Jan 14 '15 at 02:32
  • I should have mentioned but there may be cases where there is nothing to split. It works great when splitting but at rows that don't need it the resultant data frame has duplicate rows. It can end up with many. Wasn't sure what dictates it but some showed up with 20+ dupe rows – cpd1 Jan 14 '15 at 16:36
  • @AndyD, why don't you post a few more sample rows of data (preferably using `dput`) and also post your desired output. You're more likely to get better recommendations if you do so. – A5C1D2H2I1M1N2O1R2T1 Jan 15 '15 at 14:00

1 Answers1

1
str1="Test1; Test2; Test3"
str2="Other1; Other2; Other3"
Name="Andy"
Type=unlist(strsplit(str1,";"))
Other=unlist(strsplit(str2,";"))
cbind(Name,Type,Other)

> cbind(Name,Type,Other)
     Name   Type     Other    
[1,] "Andy" "Test1"  "Other1" 
[2,] "Andy" " Test2" " Other2"
[3,] "Andy" " Test3" " Other3"
qjgods
  • 958
  • 7
  • 7
  • Hi qjgod. Wouldn't this ignore the table structure? The example I gave would be just one row in a much larger table that have different names / id's and different lengths for types / other ( count for the text would always be the same for these two though) – cpd1 Jan 14 '15 at 13:27
  • @Andy D,just call this function every row,and use the `rbind` to combine together – qjgods Jan 14 '15 at 15:03
  • wouldn't it take a bit of time if there are a lot of rows then? I have close to 200,000 – cpd1 Jan 14 '15 at 16:02
  • @Andy D,if you need speed,use `Rcpp` to accelerate the program – qjgods Jan 15 '15 at 01:12