Search code examples
rif-statementnumberslevels

r if statement returns number of level rather than the level text


I have a table like the following image and I'm trying to use a simple if statement to return the country name only in cases where food is "Oranges". The 3rd column is the desired outcome, the 4th column is what I get in R.

enter image description here

In excel the formula would be:

=IF(A2="Oranges",B2,"n/a")

I have used the following r code to generate the "oranges_country" variable:

table$oranges_country <- ifelse (Food == "Oranges", Country , "n/a")

[As per the image above] The code returns the number of the level (e.g. 6) in the levels list for 'Country' rather than 'Country' itself (e.g. "Spain"). I understand where this coming from (the position in the extract as below), but it's a pain particularly when using several nested if statements.

levels(Country)
[1] "California"  "Ecuador"     "France"      "New Zealand" "Peru"        "Spain"       "UK"  

There must be a simple way to change this???

As requested in a comment: dput(table) output as follows: dput(table) structure(list(Food = structure(c(1L, 1L, 3L, 1L, 1L, 3L, 3L, 2L, 2L), .Label = c("Apples", "Bananas", "Oranges"), class = "factor"), Country = structure(c(3L, 7L, 6L, 4L, 7L, 6L, 1L, 5L, 2L), .Label = c("California", "Ecuador", "France", "New Zealand", "Peru", "Spain", "UK" ), class = "factor"), Desired_If.Outcome = structure(c(2L, 2L, 3L, 2L, 2L, 3L, 1L, 2L, 2L), .Label = c("California", "n/a", "Spain"), class = "factor"), oranges_country = c("n/a", "n/a", "6", "n/a", "n/a", "6", "1", "n/a", "n/a"), desiredcolumn = c(NA, NA, 6L, NA, NA, 6L, 1L, NA, NA)), .Names = c("Food", "Country", "Desired_If.Outcome", "oranges_country", "desiredcolumn"), row.names = c(NA, -9L), class = "data.frame")


Solution

  • Try the ifelse loop. Firstly , change Table$Country to character()

     table$Country<-as.character(Table$Country)
     table$desiredcolumn<-ifelse(table$Food == "Oranges", table$Country, NA)
    

    Here is my version:

    Food<-c("Ap","Ap","Or","Ap","Ap","Or","Or","Ba","Ba")
    Country<-c("Fra","UK","Sp","Nz","UK","Sp","Cal","Per","Eq")
    Table<-cbind(Food,Country)
    Table<-data.frame(Table)
    Table$Country<-as.character(Table$Country)
    Table$DC<-ifelse(Table$Food=="Or", Table$Country, NA)
    Table
    
    Food Country   DC
    1   Ap     Fra <NA>
    2   Ap      UK <NA>
    3   Or      Sp   Sp
    4   Ap      Nz <NA>
    5   Ap      UK <NA>
    6   Or      Sp   Sp
    7   Or     Cal  Cal
    8   Ba     Per <NA>
    9   Ba      Eq <NA>