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

别说谁变了你拦得住时间么 提交于 2021-02-10 04:36:06

问题


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.


回答1:


In Base R:

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

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

In Dplyr:

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



回答2:


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.



来源:https://stackoverflow.com/questions/31824863/how-to-simply-multiply-two-columns-of-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!