@tctccab 总是无处不在,哪里有需要就能第一时间出现在案发现场-_-!谢谢!
我也在stackoverflow搜了一下,学到了一些其他方法(不知道@tctccab的其他方法是否有这些?):
testdf <- data.frame(id = c(1,2,3,4,5),
v = c("A", "A;B", "A;C", "A;B;C", "C;D"))
testdf
## id v
## 1 1 A
## 2 2 A;B
## 3 3 A;C
## 4 4 A;B;C
## 5 5 C;D
# baseR
cbind(testdf[1], as.data.frame.matrix(t(table(stack(setNames(strsplit(as.character(testdf$v), ';'),
testdf$id))))))
## id A B C D
## 1 1 1 0 0 0
## 2 2 1 1 0 0
## 3 3 1 0 1 0
## 4 4 1 1 1 0
## 5 5 0 0 1 1
setNames(strsplit(as.character(testdf$v), ';'),
testdf$id) %>%
stack %>%
table %>%
t %>%
as.data.frame.matrix() %>%
cbind(testdf[1], .)
## id A B C D
## 1 1 1 0 0 0
## 2 2 1 1 0 0
## 3 3 1 0 1 0
## 4 4 1 1 1 0
## 5 5 0 0 1 1
# splitstackshape
library(splitstackshape)
rst3 <- cSplit_e(testdf, 'v', ';', type= 'character', fill=0, drop=TRUE)
names(rst3) <- sub('.*_', '', names(rst3))
rst3
## id A B C D
## 1 1 1 0 0 0
## 2 2 1 1 0 0
## 3 3 1 0 1 0
## 4 4 1 1 1 0
## 5 5 0 0 1 1
# qdapTools
library(qdapTools)
cbind(testdf[1],mtabulate(strsplit(as.character(testdf$v), ';')))
## id A B C D
## 1 1 1 0 0 0
## 2 2 1 1 0 0
## 3 3 1 0 1 0
## 4 4 1 1 1 0
## 5 5 0 0 1 1
# data.table
library(data.table)
setDT(testdf)
testdf[, strsplit(as.character(v), ";"), by = id] %>%
dcast(id ~ V1, function(x) {ifelse(0,0,1)}, drop=FALSE, fill=0)
## id A B C D
## 1: 1 1 0 0 0
## 2: 2 1 1 0 0
## 3: 3 1 0 1 0
## 4: 4 1 1 1 0
## 5: 5 0 0 1 1
参考资料