I have a dataset which includes (among others many variables) 5 columns indicating the country where the data is from, coded as a number. I would like to create a new variable indicating the country in plain text (e.g. Spain instead of 312).
Here is a sample of the data with only 5 rows and 2 columns for reproducibility:
c <- structure(list(CountryAP = structure(c(109, NA, 124, NA, NA), label = "Country of the Child Helpline (Asia Pacific region)", labels = c(Afghanistan = 109, `New Zealand` = 124), class = "haven_labelled"),
CountryEr = structure(c(NA, 313, NA, 287, 278), label = "Country of the Child Helpline (Europe region)", labels = c( Azerbaijan = 278, Finland = 287, Sweden = 313), class = "haven_labelled")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -5L))
I want to compute a new variable (called Country) with all the countries pulled from the numbers from the variables called CountryAP and CountryEr.
I tried this:
c <- c %>% mutate(Country = ifelse(CountryAP == 109, 'Afghanistan', ifelse(CountryAP == 124, 'New Zealand', ifelse(CountryEr == 313, 'Sweden', ifelse(CountryEr == 287, 'Finland', ifelse(CountryEr == 278, 'Azerbaijan','N/A'))))))
But although it correctly computes the rows which include values in the first variable (CountryAP), it ignores the information about the second variable (CountryEr) and gives me only this:
CountryAP CountryEr Country
1 109 NA Afghanistan
2 NA 313 NA
3 124 NA New Zealand
4 NA 287 NA
5 NA 278 NA
When I run only the CountryEr part it runs correctly.
Any idea how to make the ifelse statement accept to look at a different variable?
Any help would be much appreciated!
c
. You didn't copy all the output. – DJV Mar 12 at 16:26case_when
, instead of using nestedifelse
. – DJV Mar 12 at 16:28