From your reprex, I understand your expecting result is that sum(.) == 0
apply on row , like x[4] + y[4] = 0
, is that so ?
case_when
will apply on column and currently you don't get 999 because sum(.)
applies on each column.
If you add a helper vector with the some pre calculated you get your expected result I think
library(dplyr)
#>
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
x<-c(NA,-1,0,0,0)
y<-c(NA,23,NA,0,10)
xy<-as.data.frame(cbind(x=x,y=y))
xy
#> x y
#> 1 NA NA
#> 2 -1 23
#> 3 0 NA
#> 4 0 0
#> 5 0 10
xy%>%
# add a helper column
mutate(xpy = x + y) %>%
mutate_at(c("x","y"),
~case_when(
xpy == 0 ~ 999,
. %in% c(NA,0) ~ NA_real_,
TRUE ~ .)
) %>%
# remove the helper colum
select(-xpy)
#> x y
#> 1 NA NA
#> 2 -1 23
#> 3 NA NA
#> 4 999 999
#> 5 NA 10
Created on 2019-11-26 by the reprex package (v0.3.0)
you can also for example deal with your data.frame using pmap to do a rowise operation
library(dplyr, warn.conflicts = FALSE)
x<-c(NA,-1,0,0,0)
y<-c(NA,23,NA,0,10)
xy<-as.data.frame(cbind(x=x,y=y))
xy
#> x y
#> 1 NA NA
#> 2 -1 23
#> 3 0 NA
#> 4 0 0
#> 5 0 10
xy %>%
purrr::pmap_df(function(x, y) {
xpy = x + y
recode_custom <- function(v) {
case_when(
xpy == 0 ~ 999,
v %in% c(NA,0) ~ NA_real_,
TRUE ~ v)
}
tibble::tibble(
x = recode_custom(x),
y = recode_custom(y)
)
})
#> # A tibble: 5 x 2
#> x y
#> <dbl> <dbl>
#> 1 NA NA
#> 2 -1 23
#> 3 NA NA
#> 4 999 999
#> 5 NA 10
Created on 2019-11-26 by the reprex package (v0.3.0)