如何用dplyr的across函数替换每行首个非NA值为其与y列乘积
解决方案
Tidyverse 实现
library(tidyverse) data <- data.frame( l = c(NA, 2, NA, 4), m = c(5, NA, 7, NA), n = c(NA, 10, NA, NA), o = c(6, 7, NA, 8), y = c(2, 3, 4, 5) ) result <- data %>% rowwise() %>% mutate( # 获取当前行l:o列中第一个非NA值的列名 first_col = names(na.omit(c_across(l:o)))[1], # 定位目标列并替换值 across(all_of(first_col), ~ .x * y) ) %>% ungroup() %>% # 删除临时辅助列 select(-first_col) result
代码说明
rowwise()确保每行独立计算,避免向量运算导致的错误c_across(l:o)提取当前行指定范围的列,na.omit()过滤NA后取第一个值的列名across(all_of(first_col), ...)精准定位到需要修改的列,直接替换为原值与y列的乘积- 最后通过
select(-first_col)清理临时生成的辅助列,得到符合要求的结果
Base R 实现(可选)
如果更习惯基础R语法,也可以用循环实现:
data_copy <- data for (i in seq(nrow(data_copy))) { # 找到当前行l-o列中第一个非NA的位置 first_pos <- which(!is.na(data_copy[i, c("l", "m", "n", "o")]))[1] if (!is.na(first_pos)) { data_copy[i, first_pos] <- data_copy[i, first_pos] * data_copy[i, "y"] } } data_copy
内容的提问来源于stack exchange,提问作者AFran
相关产品推荐
相关产品推荐

