Sorting character vectors with custom order in R

时间:2018-06-04 16:46:29

标签: r sorting

I'm solving a task for my online course in R. We have the following two vectors:

Country<-c("Egypt","Peru","Belgium","Bulgaria","China","Russia")
Capital<-c("Brussels","Kairo","Moscow","Beijing","Sofia","Lima")

The task is to order the vectors and output:

Capital is the capital of Country

in the console, sorted in the right order. I've solved the task using the cat()-function:

cat(Capital[1]," is the capital of ",Country[3])

Is there a better way to do it, insted of calling the cat()-function for every pair of country-capital?

1 个答案:

答案 0 :(得分:1)

We could attempt a more "sophisticated" approach.

First we get a list with countries and their capitals from the internet using the rvest package, e.g.

library(rvest)
doc <- read_html("http://techslides.com/list-of-countries-and-capitals")
countries <- as.data.frame(html_table(doc, fill=TRUE, header=TRUE))

> head(countries, 3)
   Country.Name Capital.Name Capital.Latitude Capital.Longitude Country.Code Continent.Name
1   Afghanistan        Kabul         34.51667          69.18333           AF           Asia
2 Aland Islands    Mariehamn         60.11667          19.90000           AX         Europe
3       Albania       Tirana         41.31667          19.81667           AL         Europe

Using your country vector

Country <- c("Egypt", "Peru", "Belgium", "Bulgaria", "China", "Russia")

applying to countries data frame yields

ind <- countries$Country.Name %in% Country
paste(countries$Country.Name[ind], 'is the capital of', 
      countries$Capital.Name[ind])

[1] "Belgium is the capital of Brussels" "Bulgaria is the capital of Sofia"  
[3] "China is the capital of Beijing"    "Egypt is the capital of Cairo"     
[5] "Peru is the capital of Lima"        "Russia is the capital of Moscow"