R语言dplyr根据第二个数据框阈值将原数据框对应单元格置0
实现方案
你可以利用dplyr的across()搭配cur_column()快速匹配两个数据框的同名列做条件判断,代码如下:
library(dplyr) # 定义阈值 threshold <- 0.1 df.final <- df %>% # 仅对数值列做处理 mutate(across(where(is.numeric), # 取df.rel对应列的值做阈值判断,小于阈值的原始值改为0,否则保留 ~ ifelse(df.rel[[cur_column()]] < threshold, 0, .x)))
如果不需要单独保留相对丰度数据框df.rel,也可以一步完成计算和过滤,不用生成中间表:
threshold <- 0.1 df.final <- df %>% mutate(across(where(is.numeric), ~ ifelse(.x / sum(.x) * 100 < threshold, 0, .x)))
如果你使用的是1.0.0之前的旧版dplyr,可以用mutate_if实现相同效果:
threshold <- 0.1 df.final <- df %>% mutate_if(is.numeric, function(x) ifelse(df.rel[[deparse(substitute(x))]] < threshold, 0, x))
运行后得到的df.final和你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者CuriousDude
相关产品推荐
相关产品推荐

