Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simply multiply two columns of a dataframe? [duplicate]

My input is

a<-c(1,2,3,4)
b<-c(1,2,4,8)
df<-data.frame(cbind(a,b))

My output should be

a<-c(1,2,3,4)
b<-c(1,2,4,8)
d<-c(1,4,12,32)
df<-data.frame(cbind(a,b,c))

can i simply say df$a * df$b please help. I am getting an issue with duplication. they are getting multiplied in matrix form and there is also issue with different length columns.

like image 397
areddy Avatar asked Aug 05 '15 06:08

areddy


People also ask

Can we multiply two columns?

Multiply a column of numbers by a constant numberType =A2*$B$2 in a new column in your spreadsheet (the above example uses column D). Be sure to include a $ symbol before B and before 2 in the formula, and press ENTER.

How do you multiply a column by a constant in R?

To multiply each value in a column by a constant, we can use multiplication sign *.

How do I multiply a Dataframe in R?

To multiply only one column with a number, we can simply use the multiplication operator * but need to replace the original column with the new values.


2 Answers

In Base R:

df$c <- df$a * df$b

or df$c <- with(df, a * b)

In Dplyr:

df <- df %>% mutate(c = a * b)
like image 190
phiver Avatar answered Nov 05 '22 08:11

phiver


You must assign df$a * df$b to a new column in the dataframe.

df$c<-df$a*df$b

This adds a new column (df$c) which contains column a multiplied by column b.

like image 43
rosswalter Avatar answered Nov 05 '22 07:11

rosswalter