mercredi 8 mars 2017

How to apply multiple if statments in R?

I have a dataframe(df) that lists the countries associated with every site

Site          Country
Site1         USA
Site2         Vietnam
Site3         Spain
Site4         Germany
Site5         China

I want to attach a column, where for each country I associate its corresponding continent. I wrote a simple if loop to do this:

df$Continent <- NA
if(df$Country == "USA" |df$Country ==  "Canada" |df$Country == "Mexico")
 {df$Continent <- "North America"}
if(df$Country == "Spain" |df$Country == "France" |df$Country == "Germany")
{df$Continent <- "Europe"}
## .. etc

summary(df)

However, each time I run it the df, I find that it assigns North America to all the countries. I understand that this may sound trivial, but does it make a difference if I use if statments everywhere and not else or if else? Any suggestions for correcting this?

Aucun commentaire:

Enregistrer un commentaire