I have a data frame that is structured as follows
ID Value1 Value2
1 a;d;g;f 12;14;15;9
2 b;c;e 5;18;20
3 h;i;j 6;7;25
So I have an ID and two values, for value 1 one there are multiple options that correspond to value 2. And I want to end up with the following data frame i.e. every option of value 1 with its corresponding value 2
ID Value1 Value2
1 a 12
1 d 14
1 g 15
1 f 9
2 b 5
2 c 18
2 e 2
3 h 6
3 i 7
3 j 25
How can I script R to do this?
You can try cSplit
library(splitstackshape)
cSplit(df1, sep=";", c('Value1', 'Value2'), 'long', type.convert=TRUE)
# ID Value1 Value2
#1: 1 a 12
#2: 1 d 14
#3: 1 g 15
#4: 1 f 9
#5: 2 b 5
#6: 2 c 18
#7: 2 e 20
#8: 3 h 6
#9: 3 i 7
#10: 3 j 25
df1 <- structure(list(ID = 1:3, Value1 = c("a;d;g;f", "b;c;e", "h;i;j"
), Value2 = c("12;14;15;9", "5;18;20", "6;7;25")), .Names = c("ID",
"Value1", "Value2"), class = "data.frame", row.names = c(NA, -3L))
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