Dplyr :: rowwise, mutate and NA error

I am trying to use rowwise and mutate with a function that can return NA, but I get an error. Consider this contrived example (which, obviously, does not apply to the workaround, but illustrates the error):

It works:

 library(dplyr) data.frame(k=rnorm(10)) %>% mutate(l = ifelse(k > 0, 1, NA)) kl 1 -1.40223573 NA 2 1.47581873 1 3 0.35938746 1 4 0.87240448 1 5 -0.61991535 NA 6 -1.88152820 NA 7 0.25837350 1 8 -0.02250385 NA 9 0.92757943 1 10 0.49023792 1 

But this gives an error:

 library(dplyr) data.frame(k=rnorm(10)) %>% rowwise() %>% mutate(l = ifelse(k > 0, 1, NA)) Error: incompatible types, expecting a numeric vector 
+5
source share
1 answer

Note: I registered github issue # 1448 regarding an error as a result of this answer.

Updated October 29, 2015 . It looks like this error in rowwise() fixed. See the link above for more details.


Firstly, there is no reason to do this in different ways.

As for the error, then NA is a logical type. You will need to use NA_real_ in your ifelse() call on this line. Or, as Ben Bolker notes in the comments below, you can wrap ifelse() with as.numeric() .

 data.frame(k = rnorm(10)) %>% rowwise() %>% mutate(l = ifelse(k > 0, 1, NA_real_)) # Source: local data frame [10 x 2] # Groups: <by row> # # kl # (dbl) (dbl) # 1 -1.7105691140 NA # 2 -0.0702667985 NA # 3 -0.5505724960 NA # 4 -0.7444839870 NA # 5 -0.0005646999 NA # 6 -0.3702584194 NA # 7 0.2596026787 1 # 8 0.4149810662 NA <-- error here pointed out by David A (see comments) # 9 -0.4698540654 NA # 10 1.0961705022 1 

Note that you can also use integers, as in

 mutate(l = ifelse(k > 0, 1L, NA_integer_)) 

But you cannot mix logics and reals / integers in different ways. It seems that

+5
source

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


All Articles