【问题标题】:multi level conditional statements in rr中的多级条件语句
【发布时间】:2017-05-18 12:05:22
【问题描述】:

我对 R 很陌生,所以如果这个问题已经在之前的帖子中解决过(可能是我还不懂的语言),请原谅我。

我正在尝试根据 2 个条件生成一个新向量 (df1$response_accuracy)。第一个是向量df1$Facial.expression 的值介于1 和4 之间,向量df1$Evaluations 的值等于“Like”。匹配此条件的案例将“正确”输出到新向量中,否则将“不正确”输出。第二个参数包含一组类似的条件,但每个向量中的一组值不同(见下文)。这是我的代码:

df1$response_accuracy <- 
ifelse(df1$Facial.expression == 1:4 & df1$Evaluation == "Like", "Correct", "Incorrect",                      
ifelse(df1$Facial.expression == 5:8 & df1$Evaluation == "Dislike", "Correct", "Incorrect")
)

运行脚本后产生以下错误信息:

ifelse 中的错误(df1$Facial.expression == 1:4 & df1$Evaluation == "喜欢", : 未使用的参数 (ifelse(df1$Facial.expression == 5:8 & df1$Evaluation == "不喜欢"、"正确"、"不正确"))

我知道问题可能与 ifelse 语句支持的可接受的嵌套格式有关,但找不到适合我的命令结构的嵌套格式。

在此先感谢您对此事的帮助。

【问题讨论】:

  • df1$response_accuracy
  • @Wyldsoul 请仔细考虑df1$Facial.expression == 1:4 的含义。
  • @Imo,我明白了:df1$response_accuracy

标签: r if-statement conditional


【解决方案1】:

您不能嵌套ifelse-s。语法为ifelse(test, yes, no)。所以你需要解开它们

【讨论】:

  • 你可以,只是变得非常混乱
【解决方案2】:

这个呢? 我可以看到 2 个错误,首先如果你想在 2 个值之间,你必须这样做 x>=1 & x

#just building sample data
x<-1:10
y<-sample(c("Like","Dislike"),10,replace=TRUE)


ans1<-ifelse(x>=1 & x<=4 & y=="Like",T, F)
ans2<- ifelse(x>=5 & x<=8 & y== "Dislike", T,F)

output<-ifelse(ans1 & ans2,"Correct", "Incorrect" )

【讨论】:

    【解决方案3】:

    感谢您的回答和 cmets。我设法通过摆脱ifelse 并创建一个名为'correct_cases' 的值来找到解决方案。然后,在生成通用向量df$response_accuracy 后,我通过索引强制执行此命令;见下文

    correct_cases <- (df1$Facial.expression %in% 1:4 & 
    df1$Evaluation == "Like") |
    (df1$facial.expression %in% 5:8 & 
    df1$Evaluation == "Dislike")
    
    df1$Response_accuracy <- "Incorrect"
    
    df1$Response_accuracy[correct_cases] <- "Correct"
    

    【讨论】:

      猜你喜欢
      • 2017-06-25
      • 2014-02-05
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 2015-09-12
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多