我有以下data.frame
qs <- structure(list(Question = c("This is a question", "This is a question"),
Correct_Answer = c("D", "B"),
Answer.A = c("This is an answer", "This is an answer"),
Answer.B = c("This is an answer", "This is an answer"),
Answer.C = c("This is an answer", "This is an answer"),
Answer.D = c("This is an answer", "This is an answer"),
Explanation = c("Just because!", "Just because!"),
Response_A = c("", ""),
Response_B = c("", ""),
Response_C = c("", ""),
Response_D = c("", "")),
.Names = c("Question", "Correct_Answer", "Answer.A", "Answer.B",
"Answer.C", "Answer.D", "Explanation", "Response_A",
"Response_B", "Response_C", "Response_D"),
row.names = 1:2, class = "data.frame")
我想设置Response_X
值以匹配每个问题的Explanation
。例如,在第一行中,Correct_Answer
是D,因此Response_D
应该等于解释,另一个Responses_
应该保持空白。
我尝试过以下方法:
library(dplyr)
qs %>% rowwise() %>% mutate_(.dots=setNames(paste(Explanation),
paste0("Response_",Correct_Answer)))
它给出了:
Error in paste0("Response_", Correct_Answer) :
object 'Correct_Answer' not found
我觉得我应该在这里使用申请,但不确定如何。
答案 0 :(得分:2)
一种方法是使用自定义函数,该函数在该行的正确列中指定正确的值
assignValue <- function(x) {
qs[x, paste0("Response_", qs$Correct_Answer[x])] <<- qs$Explanation[x]
}
然后使用sapply
sapply(1:nrow(qs), function(x) assignValue(x))
注意,在函数中使用<<-
运算符。从帮助页面(?"<<-"
)
运营商&lt;&lt; - & - &gt;&gt;通常仅在函数中使用,并且通过父环境搜索要分配的变量的现有定义。如果找到这样的变量(并且它的绑定没有被锁定),那么它的值被重新定义,否则赋值发生在全局环境中
答案 1 :(得分:2)
tidyverse
解决方案。您将数据收集到&#34; tidy&#34;形式,在Correct_Answer
上有条件地变异,并将其展开。
library(tidyr)
library(dplyr)
qs %>%
gather(Resp, val, Response_A:Response_D, -Correct_Answer, -Explanation) %>% select(-val) %>%
mutate(Expl = if_else(paste("Response", Correct_Answer, sep="_") == Resp, Explanation, "")) %>%
spread(Resp, Expl)
希望这样做!
答案 2 :(得分:1)
使用常规for循环你可以这样做:
for(i in 1:nrow(qs)){
qs[i,paste('Response_',qs[i,'Correct_Answer'], sep = '')]=qs[i,'Explanation']
}
我仍然试图找出如何使用sapply更新col值。
sapply(1:nrow(qs), function(i) qs[paste('Response_',qs[i,'Correct_Answer'], sep = '')]=qs[i,'Explanation'])