R语言根据另一列数值条件替换数据框指定列对应值
需求说明
需要对数据集按规则修改列值:当b列取值不等于0时,将对应行的Variable列值从"a"替换为"b"。
示例数据
structure(list(a = c(1, 2, 3, 4, 5, 0, 0, 0, 0, 0), b = c(0, 0, 0, 0, 0, 23.5, 24.5, 28.6, 12, 17), Variable = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a")), class = "data.frame", row.names = c(NA, -10L))
期望输出结果
structure(list(a = c(1, 2, 3, 4, 5, 0, 0, 0, 0, 0), b = c(0, 0, 0, 0, 0, 23.5, 24.5, 28.6, 12, 17), Variable = c("a", "a", "a", "a", "a", "b", "b", "b", "b", "b")), class = "data.frame", row.names = c(NA, -10L))
问题复现
之前尝试的代码运行触发报错:
library(tidyverse) df = df %>% mutate(Variable = if_else(b != 0, "b", Variable))
报错信息:
Error in `mutate()`: ! Problem while computing `Variable = if_else(b != 0, "b", Variable)`. Caused by error in `if_else()`: ! `false` must be length 10 (length of `condition`) or one, not 29232.
报错原因
报错和if_else语法本身无关,核心是运行代码时当前环境中的df不是构造的10行示例数据集,而是环境中另一个同名、行数为29232的对象。if_else要求三个入参(判断条件、满足条件的返回值、不满足条件的返回值)长度要么和判断条件长度一致,要么是长度为1的标量,代码中传入的假值参数Variable取自行数不匹配的错误df,因此触发长度校验报错。
正确实现方案
方案1:tidyverse实现
先清除环境中同名干扰变量,正确赋值数据集后再执行替换逻辑即可:
library(tidyverse) # 正确构造示例数据集 df <- structure(list(a = c(1, 2, 3, 4, 5, 0, 0, 0, 0, 0), b = c(0, 0, 0, 0, 0, 23.5, 24.5, 28.6, 12, 17), Variable = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a")), class = "data.frame", row.names = c(NA, -10L)) # 按规则替换值 df <- df %>% mutate(Variable = if_else(b != 0, "b", Variable))
如果b列可能存在NA值,可将判断条件改为!is.na(b) & b != 0,避免NA值导致替换结果异常。
方案2:基础R实现
无需加载第三方包,直接按行索引赋值即可,逻辑更简洁:
# 对b不等于0的行,直接将Variable列赋值为"b" df$Variable[df$b != 0] <- "b"
内容的提问来源于stack exchange,提问作者Ed_Gravy
相关产品推荐
相关产品推荐

