本文介绍了如何在R中应用多个if语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框(df),其中列出了与每个网站相关联的国家/地区

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

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

我想附上一个专栏,每个国家都与其相应的大陆相关联。我写了一个简单的 if loop 来做这件事:

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)

但是,每当我运行df时,我发现它将北美分配给所有国家。我知道这可能听起来微不足道,但是如果我使用 if 各地的法规而不是 else 或者 if else ?有任何纠正这个的建议吗?

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?

推荐答案

我喜欢 ifelse() for像这样的事情。您可以将它与%in%运算符一起使用,如下所示:

I like ifelse() for things like this. You could use it with the %in% operator like this:

df$Continent <- ifelse(df$Country %in% c("USA", "Canada", "Mexico"),
                       "North America", df$Continent)
df$Continent <- ifelse(df$Country %in% c("Spain", "France", "Germany"),
                       "Europe", df$Continent)
df
   Site Country     Continent
1 Site1     USA North America
2 Site2 Vietnam          <NA>
3 Site3   Spain        Europe
4 Site4 Germany        Europe
5 Site5   China          <NA>

这篇关于如何在R中应用多个if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 03:14