samedi 19 août 2017

R Studio- Creating an "if else" statement with vectors > 1

I'm quite new to R and am trying to organize some data, working with the "tidyverse" package. I have a dataframe which contains "gender inequality" index scores for each country, with the dates for when the data was collected heading the columns (2000, 2005, 2010) and then the country scores in the rows.

I need to add these scores and divide them by 3, 2, or nothing depending on whether a score for one of the years is 0--so for example if I have

Year 2000 2005 2010 Norway 0 0.106 0.080

I want to add all three (0 + 0.106 + 0.080) and divide by 2. And so on for all countries, dividing by three if all years have score, and by nothing if only a year has a score

To do this I have constructed these if else statements:

GII_data_FINAL <- if (GII_data2$2000 == 0 & GII_data2$2005 != 0 & GII_data2$2010 != 0 ){GII_data2 %>% mutate(GII_mean_score = (2000+ 2005+ 2010)/2) } else if (GII_data2$2000= 0 & GII_data2$2005 == 0 & GII_data2$2010 != 0) {GII_data2 %>% mutate(GII_mean_score = 2000+ 2005+ 2010) } else if (GII_data2$2000== 0 & GII_data2$2005 != 0 & GII_data2$2010 == 0) {GII_data2 %>% mutate(GII_mean_score = 2000+ 2005+ 2010) } else if (GII_data2$2000!= 0 & GII_data2$2005!= 0 & GII_data2$2010 != 0) {GII_data2 %>% mutate (GII_mean_score = (2000+ 2005+ 2010)/3) } else if (GII_data$2000!= 0 & GII_data$2005 == 0 & GII_data$2010 != 0) {GII_data2 %>% mutate(GII_mean_score = (2000+ 2005+ 2010)/2) } else if (GII_data$2000!= 0 & GII_data$2005 == 0 & GII_data$2010 == 0) { GII_data2 %>% mutate(GII_mean_score = 2000+ 2005+ 2010) } else if (GII_data$2000!= 0 & GII_data$2005 != 0 & GII_data$2010 == 0) {GII_data2 %>% mutate(GII_mean_score = (2000+ 2005+ 2010)/2) } else if (GII_data2$2000 == 0 & GII_data2$2005 == 0 & GII_data2$2010 == 0) {GII_data2 %>% mutate(GII_mean_score = 2000+ 2005+ 2010) }

However I get the statement

"Warning messages: 1: In if (GII_data2$2000 == 0 & GII_data2$2005 != 0 & GII_data2$2010 != : the condition has length > 1 and only the first element will be used 2: In if (GII_data2$2000 & GII_data2$2005 == 0 & GII_data2$2010 != : the condition has length > 1 and only the first element will be used 3: In if (GII_data2$2000 == 0 & GII_data2$2005 != 0 & GII_data2$2010 == : the condition has length > 1 and only the first element will be used 4: In if (GII_data2$2000 != 0 & GII_data2$2005 != 0 & GII_data2$2010 != : the condition has length > 1 and only the first element will be used"

I've researched and I understand why I get this statement, but I'm not sure how else to get R to do what I want it to, as ifelse would not work with having several conditions (as far as I understand).

I'd appreciate any help at all!

Aucun commentaire:

Enregistrer un commentaire