简体   繁体   中英

multiply every column of a dataframe with another column of that dataframe in R

I would like to multiply all values of one row in a dataframe with one column at the end of the row.

eg multiply all rows by column mult (in my case there are 40 row, so an automatic solution for column selection would be nice) :

id val1 val2 val3 val4 mult ... newval1 newval2 ...
01 1 2 3 4 3 3 3 6 ...
02 1 2 3 4 6 6 6 12 ...

Thank you very much in advance and best regards! :)

data.table approach

library(data.table)
DT <- fread("id val1 val2 val3 val4 mult
01 1 2 3 4 3
02 1 2 3 4 6")

#cols to multiply
multCols <- names(DT)[grepl("^val", names(DT))]
#create new multiplied
DT[, paste0("new",multCols) := lapply(.SD, `*`, mult), .SDcols = multCols][]
#    id val1 val2 val3 val4 mult newval1 newval2 newval3 newval4
# 1:  1    1    2    3    4    3       3       6       9      12
# 2:  2    1    2    3    4    6       6      12      18      24

In dplyr , you can use across :

library(dplyr)
your_df %>% 
   mutate(across(starts_with("val"), ~ .x * mult, .names = "new{.col}"))

#  id val1 val2 val3 val4 mult newval1 newval2 newval3 newval4
#1  1    1    2    3    4    3       3       6       9      12
#2  2    1    2    3    4    6       6      12      18      24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM