Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying all columns in dataframe by single column

Tags:

r

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,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]
+ }

Thanks!

like image 770
Tanya Valkanova Avatar asked Dec 10 '18 12:12

Tanya Valkanova


2 Answers

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)
like image 53
markus Avatar answered Sep 19 '22 01:09

markus


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))
like image 28
akrun Avatar answered Sep 20 '22 01:09

akrun