PWillrodt
PWillrodt

Reputation: 31

Multiply multiple columns in a matrix by another column in same matrix in R

I've seen the answers about multiplying one matrix by another. But I have a single matrix, completely numerical. As an example:

matrix = read.table(text = 
"ID  Mult    t1  t2  t3  t4  t5
 4   0.164   10  20  30  40  50
 16  0.581   5   10  5   10  5
 42  0.008   16  17  18  19  20
 91  0.328   20  20  20  20  20
 103 0.108   103 42  56  84  61", 
 h = T)

I want to multiply t1 through t5 by the multiplier, separately, and put the results in new columns in my matrix.

I would do it column by column, but for the fact that I have over 200 columns!

Hopefully, someone can suggest a more simple fix.

Upvotes: 3

Views: 719

Answers (2)

akaDrHouse
akaDrHouse

Reputation: 2240

Some don't like loops, but I do sometimes. This is one of those times :)

mydf<-matrix
for (i in 3:length(mydf)){
  mydf[,length(mydf)+1] <- mydf$Mult * mydf[i]
}
mydf
   ID  Mult  t1 t2 t3 t4 t5   t1.1  t2.1  t3.1  t4.1  t5.1
1   4 0.164  10 20 30 40 50  1.640 3.280 4.920 6.560 8.200
2  16 0.581   5 10  5 10  5  2.905 5.810 2.905 5.810 2.905
3  42 0.008  16 17 18 19 20  0.128 0.136 0.144 0.152 0.160
4  91 0.328  20 20 20 20 20  6.560 6.560 6.560 6.560 6.560
5 103 0.108 103 42 56 84 61 11.124 4.536 6.048 9.072 6.588

Upvotes: 0

Haboryme
Haboryme

Reputation: 4761

You could do:

df=read.table(text="ID  Mult    t1  t2  t3  t4  t5
4   0.164   10  20  30  40  50
16  0.581   5   10  5   10  5
42  0.008   16  17  18  19  20
91  0.328   20  20  20  20  20
103 0.108   103 42  56  84  61",h=T)

df[,c(paste0(colnames(df[,grepl("^t.*",colnames(df),perl = T)]),"bis"))]=df[,grepl("^t.*",colnames(df),perl = T)]*df$Mult

df[,grepl("^t.*",colnames(df),perl = T)] subsets df to only have the columns starting with "t"
df[,c(paste0(colnames(df[,grepl("^t.*",colnames(df),perl = T)]),"bis"))] take the colnames() of the previous subset, and concatenate them using paste0() with "bis" or any string to indicate the change. This creates the new columns which are filled with the results of the multiplication.

> df
   ID  Mult  t1 t2 t3 t4 t5  t1bis t2bis t3bis t4bis t5bis
1   4 0.164  10 20 30 40 50  1.640 3.280 4.920 6.560 8.200
2  16 0.581   5 10  5 10  5  2.905 5.810 2.905 5.810 2.905
3  42 0.008  16 17 18 19 20  0.128 0.136 0.144 0.152 0.160
4  91 0.328  20 20 20 20 20  6.560 6.560 6.560 6.560 6.560
5 103 0.108 103 42 56 84 61 11.124 4.536 6.048 9.072 6.588

Upvotes: 1

Related Questions