【发布时间】:2014-02-19 23:10:08
【问题描述】:
我有一个调查回复数据框,其中一些列是参与者可以选择多个答案的问题(“选择所有适用的”)。
> age <- c(24, 28, 44, 55, 53)
> ethnicity <- c("ngoni", "bemba", "lozi tonga", "bemba tonga other", "bemba tongi")
> ethnicity_other <- c(NA, NA, "luvale", NA, NA)
> df <- data.frame(age, ethnicity, ethnicity_other)
我希望将这些问题设置为二元响应项,以便每个响应选项(在本例中为 ethnicity 和 ethnicity_other)都成为具有 0 或 1 的列向量。
到目前为止,我编写了一个脚本,将各个独特的响应分成一个列表 (z):
> x <- unique(as.vector(unlist(strsplit(as.character(df$ethnicity_other), " ")), mode="list"))
> y <- unique(as.vector(unlist(strsplit(as.character(df$ethnicity), " ")), mode="list"))
>
> combine <- c(x, y)
>
> z <- NULL
> for(i in combine){
> if(!is.na(i)){
> z <- append(z, i)
> }
> }
然后我从该列表中创建了新列并用 NA 值填充它们。
> for(elm in z){
> df[paste0("ethnicity_",elm)] <- NA
> }
所以现在我有 35 个额外的列,我想用 1 和 0 填充,具体取决于该列名称(或该列名称的一部分,因为我在其前面加上 ethnicity_ 前缀)可以在相应的ethnicity 或 ethnicity_other. 下的单元格我尝试了多种方法但没有好的解决方案。
【问题讨论】: