Open Side Menu Go to the Top
Register
Splitting a string and maintaining the rest of a row Splitting a string and maintaining the rest of a row

04-09-2015 , 12:38 PM
I am trying to split several strings while keeping the rows they come from intact. For example, here is my sample data:

Col A Col B Col C
40000 a|b|c d|e|f
20000 x|y|z t|u|v
10000 h|i|j m|n|o


An example result row:

40000 a d
40000 b d
40000 c d
40000 a e
40000 b e
40000 c e
40000 a f
40000 b f
40000 c f

How can I achieve this? I am working in R currently. So far, I've done:
Data$Col B = strsplit(Data$Col B, "\\|") which gives me column b in list form with each value separated by a comma.

But when i try:
Data$Col B = unlist(Data$Col B,",") I get an error explaining that the replacement has 9624 rows but the current dataset only has 3987. How can I get each value to be associated with the row it came from?
Splitting a string and maintaining the rest of a row Quote
04-09-2015 , 06:17 PM
So I figured this out after a lot of trial and error from my googling/stack overflowing. I'm going to give the solution even though no one cares just in case a future R programmer finds themselves in this spot and stumbles across this post.

library(dplyr)
library(tidyr)
my_data2 <- my_data %>% mutate(MyColumn = strsplit(MyColumn,
"\\|")) %>% unnest(MyColumn)
Splitting a string and maintaining the rest of a row Quote

      
m