mercredi 30 décembre 2015

r if statement returns number rather of level 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???

Aucun commentaire:

Enregistrer un commentaire