mardi 17 avril 2018

ifelse statement in R with different number of observations in tables

I have datasets that look something like this called KN, ON, and NH3. (My table has 50000 observations though)

KN:
high  low   calc
 1     2     3
 2     2     2
NA     NA    4
 3     3     3

ON
high   low   calc
 1      2      3
 2      2      2
 2      2      2


NH3
high   low   calc
 1      1      1
 2      2      2
 3      3      3
 4      4      4

I would like to change my KN$low variable depending on this ifelse statement. (If KN$low is NA and ON$low/NH3$low are both not NA, then make KN$low= ON$low+NH3$low for that specific observation. Else, leave KN$low as it is)

KN$low <- ifelse(is.na(KN$low) & !is.na(ON$low) & !is.na(NH3$low), ON$low + NH3$low, KN$low)

So I'd want my output to look like this:

KN:
high   low   calc
 1      2     3
 2      2     2
 NA     5     4
 3      3     3

when I try to run this, I get this error:

longer object length is not a multiple of shorter object length

Which is because (I think) ON has less rows than KN and NH3. Each observation in my table is matched with a station ID, so I think I'd have to use that somehow to pair observations for this ifelse statement (since I can't do it by observation number since each table has a different # of measurements)

Aucun commentaire:

Enregistrer un commentaire