R:将分隔的字符串转换为变量

时间:2015-04-03 05:08:23

标签: r

我有一个数据框,其中的列包含以空格分隔的字符代码列表:

"Ab B C"
""
"X C"
"N Ab F S"
:

我想将其转换为多个列,每个列对应一个不同的值,指示(在1或0处)该值在列表中找到。给出上述例子的预期结果:

df$Ab = 1,0,0,1
df$B = 1,0,0,0
df$C = 1,0,1,0
df$F = 0,0,0,1
df$N = 0,0,0,1

这样做的最佳方式是什么?

3 个答案:

答案 0 :(得分:5)

假设你开始于:

df <- data.frame(v1 = c("Ab B C", "", "X C", "N Ab F S"))

您可以从我的“splitstackshape”软件包中尝试cSplit_e

library(splitstackshape)
cSplit_e(df, "v1", sep = " ", type = "character", fill = 0)
#         v1 v1_Ab v1_B v1_C v1_F v1_N v1_S v1_X
# 1   Ab B C     1    1    1    0    0    0    0
# 2              0    0    0    0    0    0    0
# 3      X C     0    0    1    0    0    0    1
# 4 N Ab F S     1    0    0    1    1    1    0

答案 1 :(得分:4)

你可以尝试

library(qdapTools)
lst <- strsplit(df1$Col1, ' ')
cbind(df1, mtabulate(lst))
#      Col1 Ab B C F N S X
#1   Ab B C  1 1 1 0 0 0 0
#2           0 0 0 0 0 0 0
#3      X C  0 0 1 0 0 0 1
#4 N Ab F S  1 0 0 1 1 1 0

或使用base R

lvls <- sort(unique(unlist(lst)))
cbind(df1, t(vapply(lst, function(x) table(factor(x, levels=lvls)),
                numeric(length(lvls)))))

数据

df1 <- structure(list(Col1 = c("Ab B C", "", "X C", "N Ab F S")),
.Names = "Col1", row.names = c(NA, -4L), class = "data.frame")

答案 2 :(得分:2)

在基地R,另一种方法:

lst  = strsplit(df$Col1, ' ')
cols = unique(unlist(lst))

m = do.call(rbind, lapply(lst, function(u) cols %in% u +0))
colnames(m) = cols

#> m
#     Ab B C X N F S
#[1,]  1 1 1 0 0 0 0
#[2,]  0 0 0 0 0 0 0
#[3,]  0 0 1 1 0 0 0
#[4,]  1 0 0 0 1 1 1