lundi 21 août 2017

Select a group_by according to conditions in R

Let's say I have a dataframe (df) and I want to use group_by on it, to identify for instance the height of a population thanks to some people's Id

However, the choice of the Id to use in group_by is a little special : I have a first one, Id1

But sometimes, Id1 is missing in df. Fortunately, I have another Id, Id2, and is always here when Id1 == NA (but can also be here when Id1 != NA)

So is it possible to make the group_by in a certain way ? I would like something close to this (although when I tried it did not work but in the idea I think it is easily understandable):

df %>%
   group_by(if_else(is.na(Id1), Id2, Id1)) %>%
   #do something

Aucun commentaire:

Enregistrer un commentaire