Multiply columns in a data frame by a vector

前端 未结 3 1993
死守一世寂寞
死守一世寂寞 2020-12-31 05:44

What I want to do is multiply all the values in column 1 of a data.frame by the first element in a vector, then multiply all the values in column 2 by the 2nd element in the

相关标签:
3条回答
  • 2020-12-31 06:17

    We can also replicate the vector to make the lengths equal and then multiply

    d1*v1[col(d1)]
    #  c1 c2 c3
    #1  1  8 21
    #2  2 10 24
    #3  3 12 27
    

    Or use sweep

    sweep(d1, 2, v1, FUN="*")
    

    Or with mapply to multiply the corresponding columns of 'data.frame' and elements of 'vector'

    mapply(`*`, d1, v1)
    
    0 讨论(0)
  • 2020-12-31 06:23

    Transposing the dataframe works.

    c1 <- c(1,2,3)
    c2 <- c(4,5,6)
    c3 <- c(7,8,9)
    d1 <- data.frame(c1,c2,c3)
    v1 <- c(1,2,3)
    t(t(d1)*v1)
    #     c1 c2 c3
    #[1,]  1  8 21
    #[2,]  2 10 24
    #[3,]  3 12 27
    

    EDIT: If all columns are not numeric, you can do the following

    c1 <- c(1,2,3)
    c2 <- c(4,5,6)
    c3 <- c(7,8,9)
    d1 <- data.frame(c1,c2,c3)
    
    # Adding a column of characters for demonstration
    d1$c4 <- c("rr", "t", "s")
    
    v1 <- c(1,2,3)
    
    #Choosing only numeric columns
    index <- which(sapply(d1, is.numeric) == TRUE)
    d1_mat <- as.matrix(d1[,index])
    
    d1[,index] <- t(t(d1_mat)*v1)
    d1
    #  c1 c2 c3 c4
    #1  1  8 21 rr
    #2  2 10 24  t
    #3  3 12 27  s
    
    0 讨论(0)
  • 2020-12-31 06:23

    Or simply diagonalize the vector, so that each row entry is multiplied by the corresponding element in v1:

    c1 <- c(1,2,3)
    c2 <- c(4,5,6)
    c3 <- c(7,8,9)
    d1 <- as.matrix(cbind(c1,c2,c3))
    v1 <- c(1,2,3)
    
    d1%*%diag(v1)
    
         [,1] [,2] [,3]
    [1,]    1    8   21
    [2,]    2   10   24
    [3,]    3   12   27
    
    0 讨论(0)
提交回复
热议问题