Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr::rowwise, mutate, and NA error

Tags:

r

dplyr

I'm trying to use rowwise and mutate with a function that can return an NA value, but am getting an error. Consider this contrived example (which obviously is not a case for rowwise, but illustrates the error):

This works:

library(dplyr)
data.frame(k=rnorm(10)) %>% mutate(l = ifelse(k > 0, 1, NA))

           k  l
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
like image 527
Jesse Anderson Avatar asked Oct 12 '15 21:10

Jesse Anderson


1 Answers

Note: I have filed github issue #1448 regarding the error in the result of this answer.

Update Oct 29, 2015: It looks like this bug in rowwise() has been fixed. Check the link above for the details.


First off, there is no reason to make this a row-wise operation.

As far as the error goes, NA is of logical type. You will need to use NA_real_ in your call to ifelse() in this row-wise operation. 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>
# 
#                k     l
#            (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 could also use integers, as in

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

But you can't mix logicals and reals/integers in row-wise ops it seems.

like image 91
Rich Scriven Avatar answered Sep 24 '22 15:09

Rich Scriven