I have a df
like this:
df <- data.frame(FOO = c(\'A|B|C\', \'A|B\', \'B|C\', \'A\', \'C\'))
> df
FOO
1 A|B|C
2 A|B
3 B|C
4 A
5
Overlooked that OP asked for a base R
solution. Please try @AndreElrico's, @r.user.05apr's or @milan's solutions.
This can be done with cSplit_e
from the splitstackshape
package:
library(splitstackshape)
cSplit_e(
data = df,
split.col = "FOO",
sep = "|",
mode = "value",
type = "character",
fill = " ",
drop = TRUE
)
# FOO_A FOO_B FOO_C
#1 A B C
#2 A B
#3 B C
#4 A
#5 C
Does also work in case of the following df (see OP's comment above).
(df1 <- data.frame(FOO = c('A|B|C', 'A|B', 'B|C', 'A', 'C', 'B|D|F')))
# FOO
#1 A|B|C
#2 A|B
#3 B|C
#4 A
#5 C
#6 B|D|F
cSplit_e(df1, "FOO", "|", "value", "character", TRUE, fill = " ")
# FOO_A FOO_B FOO_C FOO_D FOO_F
#1 A B C
#2 A B
#3 B C
#4 A
#5 C
#6 B D F