I am trying to use sum function inside dplyr's mutate function. However I am ending up with unexpected results. Below is the code to reproduce the problem
chk1 <- data.frame(ba_mat_x=c(1,2,3,4),ba_mat_y=c(NA,2,NA,5))
I used the below code to create another column that sums up the above 2 columns
chk2 <- chk1 %>% dplyr::mutate(ba_mat=sum(ba_mat_x+ba_mat_y,na.rm = T))
I had used na.rm=T
because I have NA
s in variable ba_mat_y
. The result I got is as below
ba_mat_x ba_mat_y ba_mat
1 1 NA 13
2 2 2 13
3 3 NA 13
4 4 5 13
However, the expected result is
ba_mat_x ba_mat_y ba_mat
1 1 NA 1
2 2 2 4
3 3 NA 3
4 4 5 9