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

在R中使用case_when()基于多规则多列生成insider_class列的问题

问题:基于参数与数值生成分类列的错误修正

我需要基于data.frame的parameter和value两列,按以下规则生成新列insider_class:

  • 当parameter为pH且value满足≥6且≤9时,insider_class设为yes,否则为no
  • 当parameter为DO且value≥5.0时,insider_class设为yes

我尝试了以下代码,但部分pH值未符合规则:

数据集

df<-structure(list(Estacao2 = c("1", "1", "1", "1", "1", "1", "1", 
"1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", 
"1", "1", "1", "1", "1", "1", "1", "1", "10", "10"), parameter = c("pH", 
"DO", "pH", "DO", "pH", "DO", "pH", "DO", "pH", "DO", "pH", "DO", 
"pH", "DO", "pH", "DO", "pH", "DO", "pH", "DO", "pH", "DO", "pH", 
"DO", "pH", "DO", "pH", "DO", "pH", "DO"), value = c(4.475, 7.2, 
5.65, 5.15, 6.65, 6.425, 6.4, 6.56, 6.05, 5.533, 5.75, 5.825, 
5.625, 6.25, 5.833, 6.2, 5.35, 4.3, 5.867, 5.8, 5.375, 7.4, 5.6, 
6.45, 5.55, 6.625, 6.033, 7.667, 7.438, 7.312)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -30L), groups = structure(list(
    Estacao2 = c("1", "10"), .rows = structure(list(1:28, 29:30), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))

尝试的代码

df2<-df%>%mutate(inside_class = case_when(
    (parameter=='pH'& value %in% c(6.00:9.00) ~ 'yes'),
    (parameter=='DO' & value>=5.0 ~'yes'),
    TRUE~'no'
  ))

问题原因

代码中的value %in% c(6.00:9.00)是错误写法:6.00:9.00生成的是整数序列6、7、8、9,只会匹配这些整数值,而数据中的pH值多为小数(如6.65、6.05),自然无法被匹配,导致规则失效。另外注意你要生成的列名是insider_class,原代码里写成了inside_class,拼写不一致。

修正后的代码

使用范围判断value >=6 & value <=9替代%in%,同时修正列名拼写:

library(dplyr)

df2 <- df %>%
  mutate(insider_class = case_when(
    parameter == 'pH' & value >= 6 & value <= 9 ~ 'yes',
    parameter == 'DO' & value >= 5.0 ~ 'yes',
    TRUE ~ 'no'
  ))

验证结果

修正后,所有符合条件的pH值(如6.65、6.4、6.05、7.438等)都会被标记为yes,小于6的pH值标记为no;DO值中小于5的(如4.3)标记为no,其余≥5的标记为yes,完全符合规则要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:35:31