我有一个我想处理的调查中的“勾选所有适用项”项目。这
数据来自一个字符串变量,其中受访者所做的每个选择都是
编码成相同的变量。受访者可以从 21 个列表中选择
选项,所有适用于他们的选项。我想制作一套 21 个假人
表明是/否的变量是否受访者选择了特定的
选项。
三个示例响应是:
id x
1 3, 13
2 1, 3, 8, 9, 11, 13
3 1, 9
...
我想要的是:
id x x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13
1 3, 13 0 0 1 0 0 0 0 0 0 0 0 0 1
2 1, 3, 8, 9, 11, 13 1 0 1 0 0 0 0 1 1 0 1 0 1
3 1, 9 1 0 0 0 0 0 0 0 1 0 0 0 0
...
在我尝试这样做时,我读取了一个 id 变量和响应变量
进入列表
jp
这样每个受访者在 jp[[1]]
中都有一个 ID和他/她回复
jp[[2]]
:> jp[[2]][1:3]
[1] "3, 13 "
[2] "1, 3, 8, 9, 11, 13 "
[3] "1, 9 "
然后我通过
strsplit
清理了它们在逗号上并将其放入 jp[[4]]
:> jp[[4]][1:3]
[[1]]
[1] "3" "13"
[[2]]
[1] "1" "3" "8" "9" "11" "13"
[[3]]
[1] "1" "9"
我在所有列表元素中找到了唯一值:
> taught <- as.character(sort(as.numeric(unique(unlist(jp[[4]])))))
> taught
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "11" "12" "13" "14" "15" "16" "17" "18" "19" "20" "256"
通过一些试验和错误,我发现我可以处理每个
受访者的选择如下:
sapply(jp[[4]], function(x) any(x == "1"))
这似乎工作正常:
> table(sapply(jp[[4]], function(x) any(x == "1")))
FALSE TRUE
9404 1891
这是我期望的普及率。
但是,因为每个受访者可以有 0-21 个响应(子列表
元素),我想我需要遍历每个独特的响应
受访者的子列表,将结果写入新的列表元素。
我希望采用列表元素
jp[[4]]
,清理后的响应是并遍历“教”的每个元素以查看每个受访者中是否存在
子列表。
bla <- function(dt, lst) {
for (i in 1:length(lst)) {
subs <- list()
# apply function on each part, by row
subs[[i]] <- sapply(dt, function(x) any(x == taught[i]))
}
return(subs)
}
bla(jp[[4]], taught)
不幸的是,它似乎只适用于最后一个(第 21 个或“256”)元素
在 'taught' 中,并且不会保存到我在函数中定义的列表 'subs' 中。
> table(bla(jp[[4]], taught)[21])
FALSE TRUE
10645 650
> table(sapply(jp[[4]], function(x) any(x == "256")))
FALSE TRUE
10645 650
欢迎提出建议。谢谢。
最佳答案
,
作为数据集中的分隔符会带来问题。如果您将其替换为其他字符,例如 -
,那么它会更容易使用。假设您可以做到这一点,那么这应该可行。
tally<-function(df)
{
#create a data.frame with 23 columns, one for id, one for original x and 21 for responses
response_table=data.frame(matrix(nrow=1,ncol=23))
names(response_table)=c("id","x",paste("x",1:21,sep=""))
response_table$id=df$id
response_table$x=df$x
response_table[,3:23]=0
# Change the - to whatever separator you use
response_table[,as.numeric(unlist(str_split(df$x,'-')))+2]=1
return(response_table)
}
library(stringr)
test_data=data.frame(id=1:3,x=c("3-13","1-3-8-9-11-13","1-9"))
> test_data
id x
1 1 3-13
2 2 1-3-8-9-11-13
3 3 1-9
responses=ddply(test_data, .(id), tally)
> responses
id x x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15 x16 x17 x18 x19 x20 x21
1 1 3-13 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
2 2 1-3-8-9-11-13 1 0 1 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 0 0
3 3 1-9 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
关于R:循环检查所有应用响应以创建虚拟指标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9055516/