andrewheiss · GitHub

This is probably related a bunch of issues (#958, #1432, #1381, for example) that produce "incompatible types" errors. When making a logical test in a mutate(x = ifelse(...)) statement after defining a group, if every value of x in that group is NA, dplyr will complain about variable types. This does not happen outside of groups:

example.df <- data_frame(group_id = rep(1:5, each=10),
                         year = rep(2001:2010, times=5),
                         x1 = rep(c(rnorm(9), NA), times=5)) %>%
  bind_rows(data_frame(group_id = 6, year = 2001:2010, x1 = NA))
# This works:
example.df %>%
  mutate(x2 = ifelse(x1 > 1, 1, 0))
# This doesn't;
example.df %>%
  group_by(group_id) %>%
  mutate(x2 = ifelse(x1 > 1, 1, 0))
# Yields: "Error: incompatible types, expecting a numeric vector"

The best workaround for now is to either avoid mutate(ifelse()) calls inside groups, or to explicitly wrap ifelse statements with as.numeric, like so:

# This works:
example.df %>%
  group_by(group_id) %>%
  mutate(x2 = as.numeric(ifelse(x1 > 1, 1, 0)))

Read the original on github.com ↗