rloopsvectorvector-multiplication

Multiplication of several vectors


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)

Solution

  • 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].