Multiplying all columns in dataframe by single column

前端 未结 5 608
情书的邮戳
情书的邮戳 2020-12-21 02:10

I know it is a basic quaestion but couldnt find any solution to it. I want to multiply all columns of a dataframe by single column.

df1<-data.frame(F1=c(1         


        
相关标签:
5条回答
  • 2020-12-21 02:26

    We can vectorize the multiplication by replicating the 'C' column

    df1 * C[row(df1)]
    #     F1   F2   F3
    #1  2.0  2.0  2.0
    #2  5.0  5.0  5.0
    #3 16.0 16.0 16.0
    #4  4.5  4.5  4.5
    

    Or use the rep explicitly

    df1 * rep(C$C, ncol(df1))
    
    0 讨论(0)
  • 2020-12-21 02:34

    The overkill dplyr solution

    library(dplyr)
    
    df1 %>%
      mutate_all(.,function(col){C$C*col})
    
    0 讨论(0)
  • 2020-12-21 02:35

    There are a lot of good code only answers here, so I thought I'd explain what was going wrong.

    The problem is that you are trying to do the multiply (*) function on a list of columns, which is what a data frame is. For multiplying by a single column (C) from a second data frame (C) you would refer to that single column as either C$C C["C"], C[,1] or C[1]. If you did df1[,1]*C[,1] or one of the other ways of referring to the first column of df1 it would work fine. But the challenge is you want to do all of the columns.

    Therefore you need to use a strategy for applying the multiplication function to a list of columns. There are even more ways to do this than have already been given. For example:

     as.data.frame(lapply(df1, `*`, C$C))
    
    0 讨论(0)
  • 2020-12-21 02:36

    Also try

    df1 * t(C)
    #    F1   F2   F3
    #1  2.0  2.0  2.0
    #2  5.0  5.0  5.0
    #3 16.0 16.0 16.0
    #4  4.5  4.5  4.5
    

    When we try to multiply data frames they must be of the same size.

    df1 * C
    

    error in Ops.data.frame(df1, C) : ‘*’ only defined for equally-sized data frames

    t() turns C into a matrix, i.e. a vector with dimension attribute of length 4. This vector gets recycled when we multiply it with df1.

    What would also work in the same way (and might be faster than transposing C):

    df1 * C$C
    

    or

    df1 * unlist(C)
    
    0 讨论(0)
  • 2020-12-21 02:36

    Another solution is sweep(df1, 1, C$C, `*`), which means "sweep out" the statistic represented by C$C from each column of df1 by multiplication.

    0 讨论(0)
提交回复
热议问题