Can dplyr :: case_when return a NA and non-NA connection?

Can case_when()in dplyrreturn combination of values NAand does not NA?

When I ask you to return NAin response to one operator, but the value is not NAin response to another operator, it gives an evaluation error:

For example, I want 1for all values cyl >= 6and NAfor valuescyl < 6

> library("dplyr")
> mtcars %>% mutate(thing = case_when(cyl >= 6 ~ 1, cyl < 6 ~ NA ))

Error in mutate_impl file (.data, dots): evaluation error: it must be double, illogical.

One, both statements are fined.

This problem is absent if a return is requested for all NSs, but not a mixture NAor NAs.

For example: Return NAfor all valuescyl >= 6

> mtcars %>% mutate(thing = case_when(cyl >= 6 ~ NA))
  cyl thing
1   6    NA
2   6    NA
3   4    NA

Looks nice.

> mtcars %>% mutate(thing = case_when(cyl >= 6 ~ NA, cyl < 6 ~ NA ))
  cyl thing
1   6    NA
2   6    NA
3   4    NA

Cool.

> mtcars[1:3,] %>% mutate(thing = case_when(cyl == 6 ~ 1, cyl < 6 ~ NA, cyl > 6 ~ NA ))

mutate_impl (.data, dots):     : double, .

.

NB: mtcars[1:3,] %>% select(cyl, thing) .

+4
1

class. NA_real

mtcars %>% 
      mutate(thing = case_when(cyl >= 6 ~ 1,
                               cyl < 6 ~ NA_real_ )) 

,

mtcars[1:3,] %>% 
       mutate(thing = case_when(cyl == 6 ~ 1, 
                                cyl < 6 ~ NA_real_, 
                                cyl > 6 ~ NA_real_ ))  %>%
       select(cyl, thing)
# cyl thing
#   6     1
#   6     1
#   4    NA
+4

Source: https://habr.com/ru/post/1687849/


All Articles