我有一个"检查所有适用项"项目,来自我想处理的调查。这数据来自一个字符串变量,其中受访者做出的每个选择都是编码到同一变量中。受访者可以从 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
每个受访者都有一个 ID jp[[1]]
和他/她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"(元素在"教学"中,并且不会保存到我在函数中定义的"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
示例数据
test_data=data.frame(id=1:3,x=c("3,13","1,3,8,9,11,13","1,9"),
stringsAsFactors=FALSE)
溶液
test_data_resp <- ddply(test_data,.(id),function(data,vc) {
v1 <- as.numeric(strsplit(data$x,split=",")[[1]])
vc[v1] <- 1
return(vc)},vc = numeric(23)
)