1

需要你帮助我无法解释的具体事情。以下代码

library(dummies)
columna <- c(1,2,3)
columnb <- c("AR","AT","AF")
columnc <- c("word1", "word2", "word3")
alldata <- data.frame(columna,columnb,columnc)
alldata <- dummy.data.frame(alldata, names=c("columnc"), sep="_")
alldata

在给我

  columna columnb columnc_word1 columnc_word2 columnc_word3
1       1      AR             1             0             0
2       2      AT             0             1             0
3       3      AF             0             0             1

现在想象一下,我有

columnc <- c("word1", "word2 word3", "word3 word1")

请有人解释我如何获得?

  columna columnb columnc_word1 columnc_word2 columnc_word3
1       1      AR             1             0             0
2       2      AT             0             1             1
3       3      AF             1             0             1

问候,

4

1 回答 1

5

这是一种tidyverse方法:

library(tidyverse)
alldata %>% 
        separate_rows(columnc) %>% mutate(count = 1) %>% 
        spread(columnc, count, fill = 0, sep = "_")

#  columna columnb columnc_word1 columnc_word2 columnc_word3
#1       1      AR             1             0             0
#2       2      AT             0             1             1
#3       3      AF             1             0             1
于 2016-11-29T19:47:28.603 回答