Reputation: 229
I have a data with two columns with delimiters separating entries in each cell. Sample data would look like this:
A|B|C 20|30|40
C|D 20|40
v|M|R|Y 29|23|24|23
C 20
So i want this to look like this :
A 20
B 30
C 40
C 20
D 40
V 29
M 23
R 24
Y 23
C 20
I can use cSplit function
to delimit one column based on delimiters but i am struggling to map the alphabet to corresponding numbers in second column.
help me with a way to go about
Upvotes: 1
Views: 43
Reputation: 887088
We can use cSplit
. It works for multiple columns as well. Either use the column index or the names of the column.
library(splitstackshape)
cSplit(df1, 1:2, "|", "long")
# V1 V2
# 1: A 20
# 2: B 30
# 3: C 40
# 4: C 20
# 5: D 40
# 6: v 29
# 7: M 23
# 8: R 24
# 9: Y 23
#10: C 20
df1 <- structure(list(V1 = c("A|B|C", "C|D", "v|M|R|Y",
"C"), V2 = c("20|30|40",
"20|40", "29|23|24|23", "20")), .Names = c("V1", "V2"),
class = "data.frame", row.names = c(NA, -4L))
Upvotes: 3
Reputation: 57210
Using only base R :
# re-create your input data
Input <-
read.table(text=
'A|B|C 20|30|40
C|D 20|40
v|M|R|Y 29|23|24|23
C 20',stringsAsFactors=FALSE,col.names=c('Col1','Col2'))
# let's split...
DF2 <-
data.frame(
Col1=unlist(strsplit(Input$Col1,split='|',fixed=TRUE)),
Col2=unlist(strsplit(Input$Col2,split='|',fixed=TRUE)))
> DF2
Col1 Col2
1 A 20
2 B 30
3 C 40
4 C 20
5 D 40
6 v 29
7 M 23
8 R 24
9 Y 23
10 C 20
Upvotes: 4