sum和+都无法为每一行给出结果
df <- data.frame(x1=c(1,1),x2=c(2,3),y1=c(NA,1),y2=c(NA,1))
df <- mutate(df, cost = prod(x1,x2,na.rm = T)+prod(y1,y2,na.rm = T),na.rm=T)
结果:
x1 x2 y1 y2 cost
1 1 2 NA NA 7
2 1 3 1 1 7
预期:
x1 x2 y1 y2 cost
1 1 2 NA NA 3
2 1 3 1 1 4
We can add
rowwise
otherwiseprod
does the multiplication on the whole column whereas we need the product of sum of each row