I'm trying to do some conditional manipulation, and finding an odd dplyr error - or at least it doesn't behave the way I think it should.
Let's say I have a tibble
a <- tribble(
~x, ~y,
1, 2,
1, 3,
1, -5,
2, 1,
2, 8,
2, 9
)
Now, for each group (x), I want to bump it up if any of the values are negative so that the lowest of the formerly negative values is now 0. Let's also put in some error checking to make sure any()
is working properly.
a %>%
group_by(x) %>%
mutate(hasneg = any(y<0),
y_star = ifelse(any(y<0), y+abs(min(y, na.rm=T)), y))
This yields
# A tibble: 6 x 4
# Groups: x [2]
x y hasneg y_star
<dbl> <dbl> <lgl> <dbl>
1 1 2 TRUE 7
2 1 3 TRUE 7
3 1 -5 TRUE 7
4 2 1 FALSE 1
5 2 8 FALSE 1
6 2 9 FALSE 1
Now, hasneg
is TRUE for x=1, and FALSE for x=0, implying it worked properly on the vector. And yet, my ifelse statement has produced something odd - either 2+5 for x=1 or 1 for x=2. I would have expected 7,8,0,1,8,9.
What is going on here? Why is ifelse working strangely with these vectors in a grouped data frame?