You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言case_when函数&与|逻辑组合错误修正需求

修正后的代码
ROR1_states <- DISC_CONS_Reports %>%
  mutate(State = case_when(
    # 先确保ROR1.Conscious?为yes,再满足后面任意一个条件
    `ROR1.Conscious?` == "yes" &
      (
        `ROR1.Self-reported_State` == 'dreaming' |
        `ROR1.Focus_of_experience` %in% c('environment', 'myself') |
        `ROR1.Visual_or_Thinking` %in% c('thinking', 'seeing') |
        is.na(`ROR1.Visual_or_Thinking`)
      ) ~ "Conscious_pure",
    # 匹配第二个条件
    `ROR1.Conscious?` == "not arousable (i.e., Disconnected Consciousness ?)" ~ "Not Arousable"
  ))
问题根源

你原来的代码踩了逻辑运算符优先级的坑:R里&的优先级比|高,所以原逻辑会被解析成:
(ROR1.Conscious? == "yes" & ROR1.Self-reported_State == 'dreaming') | 其他所有条件
这就导致只要后面任意一个条件满足,哪怕ROR1.Conscious?是"no",也会被赋值为"Conscious_pure"。把所有需要和yes绑定的OR条件用括号包起来,就能让整个条件组和前面的&绑定,实现「yes为真,且后面任意一个条件成立」的预期逻辑。

额外优化提示
  • 用%in%替代多个重复的==,代码更简洁易读,比如把两个Focus_of_experience的判断合并成%in% c('environment', 'myself')
  • 你原来写的ROR1.Visual_or_Thinking == 'NA'是匹配字符串"NA",如果数据里是R原生的缺失值(NA),应该用is.na()判断,否则会漏掉这些缺失的行

内容的提问来源于stack exchange,提问作者Smemoranda95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 01:27:40