mercredi 25 octobre 2017

ifelse strange behaviour in grouped data

I come to an issue that ifelse function does not properly worked in my data frame. I want to add new column based on conditional in grouped data but it seems that the only the first element passing to new column.

df <- data.frame(ID = c(1, 1, 1 ,2, 2, 5), A = c("foo", "bar", "bar", "foo", "foo", "bar"),B=c(seq(1:6)))

ID   A B
1  1 foo 1
2  1 bar 2
3  1 bar 3
4  2 foo 4
5  2 foo 5
6  5 bar 6



df%>%
  group_by(ID)%>%
  mutate(C=ifelse(length(which(A=='bar'))>=2,B,NA))


# A tibble: 6 x 4
# Groups:   ID [3]
     ID      A     B     C
  <dbl> <fctr> <int> <int>
1     1    foo     1     1
2     1    bar     2     1
3     1    bar     3     1
4     2    foo     4    NA
5     2    foo     5    NA
6     5    bar     6    NA

I also tried do like in tidyverse/dplyr/issues/489

but it produces the same result.

What is the MATRIX;)

expected output

# A tibble: 6 x 4
# Groups:   ID [3]
     ID      A     B     C
  <dbl> <fctr> <int> <int>
1     1    foo     1     1
2     1    bar     2     2
3     1    bar     3     3
4     2    foo     4    NA
5     2    foo     5    NA
6     5    bar     6    NA

Aucun commentaire:

Enregistrer un commentaire