如何在R中基于rest6列值条件替换rest1-rest5列的值
背景
为便于复现,提供如下数据集:
data <- structure(list(rest1 = c(1, 1, 0, 1, 1, 1, 0, 1, 0, 1), rest2 = c(1, 0, 1, 0, 0, 1, 1, 0, 0, 0), rest3 = c(1, 0, 0, 0, 0, 1, 0, 1, 0, 0), rest4 = c(1, 0, 0, 0, 0, 1, 0, 0, 0, 0), rest5 = c(1, 1, 0, 0, 0, 1, 0, 1, 0, 1), rest6 = c(0, 0, 1, 0, 0, 0, 1, 0, 1, 0)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L))
当前数据输出:
A tibble: 10 x 6 rest1 rest2 rest3 rest4 rest5 rest6 <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 1 1 1 1 0 2 1 0 0 0 1 0 3 0 1 0 0 0 1 4 1 0 0 0 0 0 5 1 0 0 0 0 0 6 1 1 1 1 1 0 7 0 1 0 0 0 1 8 1 0 1 0 1 0 9 0 0 0 0 0 1 10 1 0 0 0 1 0
问题需求
需要基于rest6列的值修改数据:当rest6的值为1时,将对应行的rest1-rest5列全部改为0。其中第3、7行需要修正,期望输出如下:
rest1 rest2 rest3 rest4 rest5 rest6 <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 1 1 1 1 1 0 2 1 0 0 0 1 0 3 0 0 0 0 0 1 4 1 0 0 0 0 0 5 1 0 0 0 0 0 6 1 1 1 1 1 0 7 0 0 0 0 0 1 8 1 0 1 0 1 0 9 0 0 0 0 0 1 10 1 0 0 0 1 0
过往尝试
我用基础R尝试实现,逻辑是当rest6等于1且对应观测值为1时设为0,否则保留原值,但未成功:
data <- ifelse(data$rest6 == 1 & data[,c(2:5) == 1], 0, data[,c(2:6)])
也曾尝试用function()定位赋值位置,恳请提供解决方法。
解决方法
方法1:基础R实现
直接定位rest6 == 1的行,批量修改rest1-rest5列:
# 筛选rest6为1的行索引 target_rows <- data$rest6 == 1 # 将这些行的rest1到rest5列设为0 data[target_rows, c("rest1", "rest2", "rest3", "rest4", "rest5")] <- 0
这种方式逻辑清晰,避免了ifelse的维度匹配问题,直接对目标行和列赋值,效率更高。
方法2:tidyverse(dplyr)实现
如果熟悉tidyverse生态,用mutate配合across可以更简洁地批量处理列:
library(dplyr) data <- data %>% mutate(across(rest1:rest5, ~ ifelse(rest6 == 1, 0, .x)))
across(rest1:rest5)指定需要处理的列范围,ifelse(rest6 == 1, 0, .x)表示当rest6为1时替换为0,否则保留原列值。
内容的提问来源于stack exchange,提问作者Harambe
相关产品推荐
相关产品推荐

