我有以下数据帧:
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"))
它看起来像这样:
> dat
# A tibble: 3 × 3
residue PP1 KF2
<chr> <dbl> <dbl>
1 A -0.96 -1.67
2 R 0.8 1.27
3 N 0.82 -0.07
我想做的是将除residue
之外的每一列与此处对应的tibble相乘:
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))
> weight_dat
# A tibble: 3 × 2
residue weight
<chr> <dbl>
1 A 2
2 R 2
3 N 1
导致
residue PP1 KF2
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
实际上CCD_ 2具有3行和数千列。
使用match
+*
:
w <- weight_dat$weight[match(dat$residue, weight_dat$residue)]
cbind(dat[1], dat[-1] * w)
residue PP1 KF2
1 A -1.92 -3.34
2 R 1.60 2.54
3 N 0.82 -0.07
dplyr
选项:
library(dplyr)
dat %>%
mutate(across(-1, `*`, weight_dat$weight[match(dat$residue, weight_dat$residue)]))