Home > Software design >  Multiplication of selected columns by a given vector
Multiplication of selected columns by a given vector

Time:10-26

I have been struggling with a task in R for some time, which seems to be easy.

suppose this is my sample data:

df <- data.frame(a=c(2,2,7),b=c(1,4,3),c=c(9,5,3))
v <- c(1,2,3)

now I would like to multiply each column by the corresponding vector element e.g. first column by v[1], second column by v[2]etc..

expected output:

  a b  c
1 2 2 27
2 2 8 15
3 7 6  9

The target data is much larger and consists of integers and floating point numbers. Thank you in advance!

CodePudding user response:

You can use sweep:

sweep(df, 2, v, FUN="*")

Second option is mapply:

mapply(`*`, df, v)

Or with transposing:

t(t(df)*v)

CodePudding user response:

You can try col

> v[col(df)] * df
  a b  c
1 2 2 27
2 2 8 15
3 7 6  9

CodePudding user response:

apply(df, 1, function(x) x * v) |> t()

or

t(apply(df, 1, function(x) x * v))
  • Related