Multiplying all columns in dataframe by single column

前端 未结 5 609
情书的邮戳
情书的邮戳 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: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)
    

提交回复
热议问题