Search code examples
rdataframemultiplication

How to simply multiply two columns of a dataframe?


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.


Solution

  • In Base R:

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

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

    In Dplyr:

    df <- df %>% mutate(c = a * b)