我想查看每个响应的多个列,如果这些列中只有一列包含特定字符串,则将该列名称放入新列中。
示例数据框:
data <- structure(list(ParticipantID = 1:5, Usual = c("Pear", "Pear",
"Apple", NA, NA), Pear_Freq = c("3 or more times a week", "3 or more times a week",
"Once a week", "Once a week", "3 or more times a week"), Apple_Freq = c("Never",
"Once a week", "3 or more times a week", "Never", "3 or more times a week"
), Peach_Freq = c("Once a week", "Never", "Never", "3 or more times a week",
"Once a week")), .Names = c("ParticipantID", "Usual", "Pear_Freq",
"Apple_Freq", "Peach_Freq"), class = "data.frame", row.names = c(NA,
-5L))
所以我希望摆脱它的是一个包含以下内容的新专栏:
ParticipantID Newcol
1 Pear
2 Pear
3 Apple
4 Peach
5 NA
(作为检查人们说什么和做了什么匹配,以及在'通常'栏中填写空白的方式)
到目前为止,我有一些代码将计数放入一个新列中,这样我就可以选择在一列(而不是2或0)中每周只勾选3次或更多次的人:
test$tempcol <- NA
test$tempcol <- apply(test[,Freqcols], 1, function(x) sum(grepl("3 or more times a week", x)))
(我觉得我不需要使用grepl
,因为我希望匹配整个单元而不是模式,真的)
然后我试图使用哪个来获取每个响应者的列的索引,其中包含“每周3次或更多次”,如下所示:
which(apply(test, 1, function(x) any(grepl("3 or more times a week", x))))
但是,当然,这只是告诉我每个人每周至少要说一次,每次3次或更多次。
然后我希望用它来将列标题的Fruit位粘贴到一个新的单元格中,但我对如何实际达到这一点有点迷失:(任何建议都会非常感激。< / p>
答案 0 :(得分:1)
你可以试试这个:
data$newcol <- apply(data[3:5], 1, function(x)
ifelse(length(which(x == "3 or more times a week")) != 1, NA,
unlist(strsplit(names(data[3:5])[which(x == "3 or more times a week")], "_")))[1])
# ParticipantID Usual Pear_Freq Apple_Freq Peach_Freq newcol
#1 1 Pear 3 or more times a week Never Once a week Pear
#2 2 Pear 3 or more times a week Once a week Never Pear
#3 3 Apple Once a week 3 or more times a week Never Apple
#4 4 <NA> Once a week Never 3 or more times a week Peach
#5 5 <NA> 3 or more times a week 3 or more times a week Once a week <NA>
您将开始检查每周3次或更多次的响应频率&#34;使用which
并且如果它出现多于或少于一次,您将返回NA
。如果只出现一次,which
会告诉您列出的列的索引,并使用names(data[3:5])
找出匹配的列名。为了得到名称的水果位,你用&#34; _&#34;,unlist
将结果列表分开,并使用它的第一位只写入新列。