1

I have the following data frame:

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"))

It looks like this:

> 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

What I want to do is to multiply every column other than residue with the corresponding tibble here:

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

Resulting in

  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

in reality the dat has 3 rows and thousands of columns.

neversaint
  • 60,904
  • 137
  • 310
  • 477

1 Answers1

0

With 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 option:

library(dplyr)
dat %>% 
  mutate(across(-1, `*`, weight_dat$weight[match(dat$residue, weight_dat$residue)]))
Maël
  • 45,206
  • 3
  • 29
  • 67