Home > front end >  multiply every column of a dataframe with another column of that dataframe in R
multiply every column of a dataframe with another column of that dataframe in R

Time:05-13

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

e.g. 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! :)

CodePudding user response:

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

CodePudding user response:

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
  • Related