需要你的帮助来解决我无法解释的特定事情。 以下代码
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
此致
答案 0 :(得分: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