0

我的df2

          League freq
18       England  108
27         Italy   79
20       Germany   74
43         Spain   64
19        France   49
39        Russia   34
31        Mexico   27
47        Turkey   24
32   Netherlands   23
37      Portugal   21
49 United States   18
29         Japan   16
25          Iran   15
7         Brazil   13
22        Greece   13
14         Costa   11
45   Switzerland   11
5        Belgium   10
17       Ecuador   10
23      Honduras   10
42   South Korea    9
2      Argentina    8
48       Ukraine    7
3      Australia    6
11         Chile    6
12         China    6
15       Croatia    6
35        Norway    6
41      Scotland    6
34       Nigeria    5

我尝试选择europe.

europe <- subset(df2, nrow(x=18, 27, 20) select=c(1, 2))

europe选择, africa, Asia... from的最有效方法是什么df2

4

2 回答 2

5

您要么需要手动确定哪些国家在哪些大洲,要么您可以从某个地方刮取这些信息:

(使用 XML 包将 html 表抓取到 R 数据帧中的基本策略)

library(XML)
theurl <- "http://en.wikipedia.org/wiki/List_of_European_countries_by_area"
tables <- readHTMLTable(theurl)
library(stringr)
europe_names <- str_extract(as.character(tables[[1]]$Country),"[[:alpha:] ]+")
head(sort(europe_names))
## [1] "Albania"    "Andorra"    "Austria"    "Azerbaijan" "Belarus"     
## [6] "Belgium"   
## there's also a 'Total' entry in here but it's probably harmless ...
subset(df2,League %in% europe_names)

当然,对于亚洲、美洲等,您必须再次弄清楚这一点。

于 2014-06-05T22:16:25.980 回答
3

所以这里有一种与@BenBolker 略有不同的方法,它使用了这个countrycode包。

library(countrycode)
cdb <- countrycode_data         # database of countries

df2[toupper(df2$League) %in% cdb[cdb$continent=="Europe",]$country.name,]
#         League freq
# 27       Italy   79
# 20     Germany   74
# 43       Spain   64
# 19      France   49
# 32 Netherlands   23
# 37    Portugal   21
# 22      Greece   13
# 45 Switzerland   11
# 5      Belgium   10
# 48     Ukraine    7
# 15     Croatia    6
# 35      Norway    6

您将遇到的一个问题是“英格兰”不是任何数据库中的国家(而是“英国”),因此您必须将其作为一种特殊情况来处理。

此外,该数据库将“美洲”视为一个大陆。

df2[toupper(df2$League) %in% cdb[cdb$continent=="Americas",]$country.name,]

所以要获得南美洲,您必须使用该region字段:

df2[toupper(df2$League) %in% cdb[cdb$region=="South America",]$country.name,]
#       League freq
# 7     Brazil   13
# 17   Ecuador   10
# 2  Argentina    8
# 11     Chile    6
于 2014-06-06T03:29:14.963 回答