为什么dplyr无法按行生成结果?

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
评论
qet
qet

We can add rowwise otherwise prod does the multiplication on the whole column whereas we need the product of sum of each row

library(dplyr)
df %>%
    rowwise %>%
    mutate(cost = prod(x1,x2,na.rm = TRUE) + prod(y1,y2,na.rm = TRUE)) %>%
    ungroup
# A tibble: 2 x 5
#     x1    x2    y1    y2  cost
#  <dbl> <dbl> <dbl> <dbl> <dbl>
#1     1     2    NA    NA     3
#2     1     3     1     1     4
点赞
评论