匹配两个不同数据框的两列字符并标记它们

matching characters of two columns of two different data frames and label them

所以这是我的主要数据

 Country Consumption Rank
Belarus        17.5    1
 Moldova        16.8    2
Lithuania        15.4    3
  Russia        15.1    4
 Romania        14.4    5
 Ukraine        13.9    6

我还收集了这些大陆的其他数据框,例如:

 europe
Albania
 Andorra
Armenia
 Austria
Azerbaijan
Belarus

或其他数据框,如

  asia
Afghanistan
 Bahrain
 Bangladesh
  Bhutan
  Brunei

6缅甸(缅甸)

我想将我的数据中的国家与我拥有的大洲国家数据框相匹配,然后用欧洲或亚洲等大洲标记它们

这是我管理的代码,但与它们不匹配,所以 else if 只执行:

 if ( data$Country %in% europe$europe) {
 data$con<-c("Europe")
} else if ( data$Country %in% asia$asia) {
 data$con<-c("asia")
 } else if ( data$Country %in% africa$africa) {
data$con<-c("africa")
    } else
    data$con<-c("ridi")

提前致谢。

这是使用 ifelse 的一种方法。我稍微修改了您的数据,因此您可以看到它适用于亚洲和欧洲

# get your data
df <- read.table(text="Country Consumption Rank
Belarus        17.5    1
                  Brunei        16.8    2
                  Lithuania        15.4    3
                  Austria        15.1    4
                  Romania        14.4    5
                  Ukraine        13.9    6
                  Bangladesh      24.2   5", header=T)

df.europe <- read.table(text=" europe
Albania
                          Andorra
                          Armenia
                          Austria
                          Azerbaijan
                          Belarus", header=T, as.is=T)

df.asia <- read.table(text="asia
Afghanistan
                  Bahrain
                  Bangladesh
                  Bhutan
                  Brunei", header=T, as.is=T)

# use ifelse to get categories
df$con <- ifelse(df$Country %in% df.europe$europe, "europe", 
                 ifelse(df$Country %in% df.asia$asia, "asia", NA))

将嵌套 ifelse 保持在最低限度通常是个好主意,但对于这样一个包含几千个观察值的数据集,就没问题了。

首先,构建从国家到大陆的地图:

continent_map = stack(c(europe, asia))
names(continent_map) <- c("Country", "Continent")

然后,使用match:

dat["Continent"] = continent_map$Continent[ match(dat$Country, continent_map$Country) ]

    Country Consumption Rank Continent
1   Belarus        17.5    1    europe
2   Moldova        16.8    2      <NA>
3 Lithuania        15.4    3      <NA>
4    Russia        15.1    4      <NA>
5   Romania        14.4    5      <NA>
6   Ukraine        13.9    6      <NA>

通常,您应该将相关数据保存在单个结构中,例如 continent_map(而不是像 OP 的 asiaeurope 那样的许多单独的位置)。


使用的数据:

dat = structure(list(Country = c("Belarus", "Moldova", "Lithuania", 
"Russia", "Romania", "Ukraine"), Consumption = c(17.5, 16.8, 
15.4, 15.1, 14.4, 13.9), Rank = 1:6), .Names = c("Country", "Consumption", 
"Rank"), row.names = c(NA, -6L), class = "data.frame")
europe = structure(list(europe = c("Albania", "Andorra", "Armenia", "Austria", 
"Azerbaijan", "Belarus")), .Names = "europe", row.names = c(NA, 
-6L), class = "data.frame")
asia = structure(list(asia = c("Afghanistan", "Bahrain", "Bangladesh", 
"Bhutan", "Brunei")), .Names = "asia", row.names = c(NA, -5L), class = "data.frame")