0

A small sample of my data is as follows:

A=c(0.1,    0.3,    0.6,    0.1)

dat<-read.table (text=" D1 D2 D3 D4
10  11  13  14
9   8   8   0
70  100 2   3
4   3   3   200
1   2   3   4

", header=TRUE)

The logic is that 0.1 x D1, 0.3xD2, 0.6xD3 and 0.1xD4.

Here is the outcome

1   3.3 7.8 1.4
0.9 2.4 4.8 0
7   30  1.2 0.3
0.4 0.9 1.8 20
0.1 0.6 1.8 0.4

Please assume I have more than 4 Ds

user330
  • 1,256
  • 1
  • 7
  • 12

1 Answers1

2

A possible solution, using dplyr:

library(dplyr)

dat %>% 
  mutate(across(everything(), ~ .x * A[which(names(dat) == cur_column())]))

#>    D1   D2  D3   D4
#> 1 1.0  3.3 7.8  1.4
#> 2 0.9  2.4 4.8  0.0
#> 3 7.0 30.0 1.2  0.3
#> 4 0.4  0.9 1.8 20.0
#> 5 0.1  0.6 1.8  0.4

Another possible solution, in base R:

as.data.frame(t(apply(dat, 1, \(x) x * A)))

Yet another possible solution, using purrr::map2_df:

purrr::map2_df(dat, A, `*`)

Or even:

mapply(`*`, dat, A)
PaulS
  • 21,159
  • 2
  • 9
  • 26