Multiplying all columns in dataframe by single column

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

提交回复
热议问题