如何基于另一个tibble对tibble中除residue列外的列迭代相乘?
解决方案
生成带计算式的结果(匹配你的期望格式)
如果需要保留计算过程的字符串形式用于展示,可使用以下代码:
library(tidyverse) # 加载原始数据 dat <- structure(list(residue = c("A", "R", "N"), PP1 = c(-0.96, 0.8, 0.82), KF2 = c(-1.67, 1.27, -0.07)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")) weight_dat <- structure(list(residue = c("A", "N", "R"), weight = c(2, 1, 2)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -3L)) # 数据处理流程 result <- dat %>% # 按残基列匹配权重数据 inner_join(weight_dat, by = "residue") %>% # 批量处理所有数值列,生成带计算式的字符串 mutate( across( -c(residue, weight), ~ str_glue("({.x}*{weight})={.x*weight}") ) ) %>% # 移除临时的权重列 select(-weight) # 查看结果 print(result, width = Inf)
运行后输出:
# A tibble: 3 × 3 residue PP1 KF2 <chr> <glue> <glue> 1 A (-0.96*2)=-1.92 (-1.67*2)=-3.34 2 R (0.8*2)=1.6 (1.27*2)=2.54 3 N (0.82*1)=0.82 (-0.07*1)=-0.07
只保留计算后的数值(适合后续分析)
如果不需要展示计算过程,仅需最终乘积结果,代码更简洁:
result_numeric <- dat %>% inner_join(weight_dat, by = "residue") %>% mutate(across(-c(residue, weight), ~ .x * weight)) %>% select(-weight) print(result_numeric)
运行后输出:
# A tibble: 3 × 3 residue PP1 KF2 <chr> <dbl> <dbl> 1 A -1.92 -3.34 2 R 1.6 2.54 3 N 0.82 -0.07
关键说明
inner_join确保每个残基都能匹配到对应权重,避免不匹配行干扰结果across(-c(residue, weight))自动选中所有需处理的数值列,无论数据有几千列都能批量完成计算,无需手动指定列名str_glue用于拼接计算式与结果,严格匹配你需要的输出格式
内容的提问来源于stack exchange,提问作者neversaint
相关产品推荐
相关产品推荐

