Reputation: 209
I want to multiply all columns of a dataframe by single column.
df1 <- data.frame(F1=c(1,5,8,9),F2=c(1,5,8,9),F3=c(1,5,8,9))
> df1
F1 F2 F3
1 1 1 1
2 5 5 5
3 8 8 8
4 9 9 9
C <- data.frame(C=c(2,1,2,0.5))
> C
C
1 2.0
2 1.0
3 2.0
4 0.5
I wanna multiply each column of df1
by C.
I have tried:
df2<-df1[,c(1:3)]*C[,1]
df2<-df1*C
df2< df1%*%C
and
for(i in 2:length(names(b))) {
+ df2 <- C[, 1] * b[, i]
+ }
Upvotes: 6
Views: 11090
Reputation: 26343
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)
Upvotes: 6
Reputation: 3943
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.
Upvotes: 3
Reputation: 6755
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))
Upvotes: 3
Reputation: 5673
The overkill dplyr solution
library(dplyr)
df1 %>%
mutate_all(.,function(col){C$C*col})
Upvotes: 4
Reputation: 887078
We can vectorize the multiplication by rep
licating 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))
Upvotes: 5