Reputation: 25
I have 10 vectors (v_1 to v_10) and I need all of them multiplied with another vector v_mult (i.e. v_1*v_mult, v_2*v_mult etc.). How to I solve this problem within a for-loop? Im stuck to the loop-solution (which I do not find) because it is part of a larger analysis.
v_10<-c(2, 3, 5, 8)
v_20<-c(3, 9, 0, 1)
v_30<-c(15, 9, 6, 0)
v_40<-c(4, 9, 6, 1)
v_50<-c(1, 7, 3, 9)
v_60<-c(5, 9, 5, 1)
v_70<-c(5, 8, 2, 6)
v_80<-c(5, 8, 1, 6)
v_90<-c(5, 0, 1, 6)
v_10<-c(2, 8, 1, 0)
v_mult<-c(8, 5, 1, 9)
Upvotes: 0
Views: 87
Reputation: 886938
We can get all the vector objects in a list
using mget
and multiply each element of the list
with 'v_mult' using Map
.
Map('*',mget(paste('v', seq(10, 100, by=10), sep="_")), list(v_mult))
Or use set
from data.table
which would be very fast as it doesn't have the .[data.table
overhead.
library(data.table)
DT <- setDT(mget(paste('v', seq(10, 100, by=10), sep="_")))
for(j in seq_along(DT)){
set(DT, i=NULL, j= j, value= DT[[j]]*v_mult)
}
Upvotes: 0
Reputation: 132576
Those vectors should be all together in a matrix:
vlist <- mget(ls(pattern = "v_[[:digit:]*]"))
m <- do.call(cbind, vlist)
m * v_mult
# v_10 v_20 v_30 v_40 v_50 v_60 v_70 v_80 v_90
#[1,] 16 24 120 32 8 40 40 40 40
#[2,] 40 45 45 45 35 45 40 40 0
#[3,] 1 0 6 6 3 5 2 1 1
#[4,] 0 9 0 9 81 9 54 54 54
You can of course extract each vector from the matrix using column subsetting, e.g., m[, "v_10"]
or m[, 1]
.
Upvotes: 1