如何将列拆分为每个值的列

时间:2018-01-19 14:31:53

标签: r

是否有根据值将列拆分为多列的快速方法?
例如,列x具有值(a,b,c,d)。现在我想将列x分成4列(a,b,c,d),值为0或1.如下例所示:

x | a b c d
a | 1 0 0 0
c | 0 0 1 0
b | 0 1 0 0
b | 0 1 0 0
d | 0 0 0 1

3 个答案:

答案 0 :(得分:0)

试试这个:

as.data.frame(do.call(rbind,lapply(df$x,table)))

答案 1 :(得分:0)

这里有各种选择:

x = c("a","c","b","b","d")

library(dummies)

dummy(x)

#      xa xb xc xd
# [1,]  1  0  0  0
# [2,]  0  0  1  0
# [3,]  0  1  0  0
# [4,]  0  1  0  0
# [5,]  0  0  0  1

dummy.data.frame(data.frame(x))

#   xa xb xc xd
# 1  1  0  0  0
# 2  0  0  1  0
# 3  0  1  0  0
# 4  0  1  0  0
# 5  0  0  0  1


library(tidyverse)

data.frame(x) %>%
  mutate(id = row_number(),
         counts = 1) %>%
  spread(x, counts, fill = 0) %>%
  select(-id)

#   a b c d
# 1 1 0 0 0
# 2 0 0 1 0
# 3 0 1 0 0
# 4 0 1 0 0
# 5 0 0 0 1

答案 2 :(得分:0)

对于数字值,它可以这样工作:

install.packages("splitstackshape")
library(splitstackshape)
splitted <- cSplit_e(data, "x", "|", type = "numeric", fill = 0, drop = T)

对于所有值,它将像这样工作(但您必须在之后删除原始列):

install.packages("dummies")
library(dummies)
splitted <- cbind(data, dummy(data$x, sep = "_"))