Just came across this question as it was linked in a recent question on SO.
Shameless plug of an answer: Use cSplit
from my "splitstackshape" package:
df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
library(splitstackshape)
cSplit(df, "FOO", "|")
# ID FOO_1 FOO_2
# 1 11 a b
# 2 12 b c
# 3 13 x y
This particular function also handles splitting multiple columns, even if each column has a different delimiter:
df <- data.frame(ID=11:13,
FOO=c('a|b','b|c','x|y'),
BAR = c("A*B", "B*C", "C*D"))
cSplit(df, c("FOO", "BAR"), c("|", "*"))
# ID FOO_1 FOO_2 BAR_1 BAR_2
# 1 11 a b A B
# 2 12 b c B C
# 3 13 x y C D
Essentially, it's a fancy convenience wrapper for using read.table(text = some_character_vector, sep = some_sep)
and binding that output to the original data.frame
. In other words, another A base R approach could be:
df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
cbind(df, read.table(text = as.character(df$FOO), sep = "|"))
ID FOO V1 V2
1 11 a|b a b
2 12 b|c b c
3 13 x|y x y