girls.textdata=
"row.name|name|age|hobby|height
g1|Лена|19|лыжи|166
g2|Жанна|22|вышивка|156,5
g3|Даша|29|лыжи|180
g4|Ира|26|танцы|170
g5|Зина|16|танцы|160"
girls <- read.delim(header=T,
sep="|" , dec = ",",
text= girls.textdata,
row.names = 1,
stringsAsFactors = F
)
boys.textdata=
"row.name|name|age|hobby|height
b1|Гена|19|лыжи|188
b2|Женя|32|мотоцикл|166,5
b3|Саша|29|лыжи|180
b4|Дима|26|танцы|170"
boys <- read.delim(header=T,
sep="|" , dec = ",",
text= boys.textdata,
row.names = 1,
stringsAsFactors = F
)
dir.create("data")
## Warning in dir.create("data"): 'data' уже существует
url_world_data <- "http://crow.academy.ru/~ikocherg/stud_do/2015vesna/world.txt.zip"
#download.file(url_world_data,destfile = "data/world.txt.zip")
# unzip("data/world.txt.zip",exdir = "data")
city <- read.csv2("data/city.txt",as.is=T)
country <- read.csv2("data/country.txt",as.is=T)
Шпаргалка по пакету находится в разделе шпаргалок RStudio под именем Data Wrangling Cheat Sheet
library(dplyr)
## Warning: package 'dplyr' was built under R version 3.1.3
Преобразуем фреймы данных в усовершенстованные (local data frame), которые поддерживает пакет dplyr.
city_t <- tbl_df(city)
country_t <- tbl_df(country)
База world
city_t
## Source: local data frame [4,079 x 5]
##
## CityID Name CountryCode District Population
## (int) (chr) (chr) (chr) (int)
## 1 1 Kabul AFG Kabol 1780000
## 2 2 Qandahar AFG Qandahar 237500
## 3 3 Herat AFG Herat 186800
## 4 4 Mazar-e-Sharif AFG Balkh 127800
## 5 5 Amsterdam NLD Noord-Holland 731200
## 6 6 Rotterdam NLD Zuid-Holland 593321
## 7 7 Haag NLD Zuid-Holland 440900
## 8 8 Utrecht NLD Utrecht 234323
## 9 9 Eindhoven NLD Noord-Brabant 201843
## 10 10 Tilburg NLD Noord-Brabant 193238
## .. ... ... ... ... ...
country_t
## Source: local data frame [239 x 15]
##
## CountryCode Name Continent
## (chr) (chr) (chr)
## 1 ABW Aruba North America
## 2 AFG Afghanistan Asia
## 3 AGO Angola Africa
## 4 AIA Anguilla North America
## 5 ALB Albania Europe
## 6 AND Andorra Europe
## 7 ANT Netherlands Antilles North America
## 8 ARE United Arab Emirates Asia
## 9 ARG Argentina South America
## 10 ARM Armenia Asia
## .. ... ... ...
## Variables not shown: Region (chr), SurfaceArea (dbl), IndepYear (int),
## Population (int), LifeExpectancy (dbl), GNP (dbl), GNPOld (dbl),
## LocalName (chr), GovernmentForm (chr), HeadOfState (chr), Capital (int),
## Code2 (chr)
База бабушек у подъезда
girls
## name age hobby height
## g1 Лена 19 лыжи 166.0
## g2 Жанна 22 вышивка 156.5
## g3 Даша 29 лыжи 180.0
## g4 Ира 26 танцы 170.0
## g5 Зина 16 танцы 160.0
boys
## name age hobby height
## b1 Гена 19 лыжи 188.0
## b2 Женя 32 мотоцикл 166.5
## b3 Саша 29 лыжи 180.0
## b4 Дима 26 танцы 170.0
Задание 1 Бабушки на лавочки у подъезда хотят обсудить возможные пары девочек и мальчиков из их подъезда. Они решили рассмотреть пары с общими хобби и добавили еще дополнительные фильтры : разница в возрасте не должна превышать 6 лет и выстота девушки должна быть строго меньше высоты юноши. Запрос должен выдать такой результат:
inner_join(x = girls,y=boys,by=c("hobby")) %>%
filter(abs(age.x-age.y) <=6 , height.x<height.y)
## name.x age.x hobby height.x name.y age.y height.y
## 1 Лена 19 лыжи 166 Гена 19 188
Задание 2 Показать страны, удовлетворяющие условию Region==“Baltic Countries” упорядочив их по убыванию населения (Population). Выдайте только столбцы Name, Population, SurfaceArea. Ожидаемый результат:
country_t %>%
filter(Region=="Baltic Countries") %>%
arrange(desc(Population)) %>%
select(Name,Population,SurfaceArea)
## Source: local data frame [3 x 3]
##
## Name Population SurfaceArea
## (chr) (int) (dbl)
## 1 Lithuania 3698500 65301
## 2 Latvia 2424200 64589
## 3 Estonia 1439200 45227
Задание 3 Соедините таблицы city (city_t) и country (country_t) по полю CountryCode. Выдайте только информацию про те города, где население города (Population.x) больше чем количество граждан стран, в которой он расположен (Population.y). Выдайте в результат только столбцы, в имена которых содержат (containts() ) строки “Population”, “Name”. Ожидаемый результат:
inner_join(city_t,country_t,by=c("CountryCode" = "CountryCode")) %>%
filter(Population.x>Population.y) %>%
select(contains("Population"), contains("Name"))
## Source: local data frame [2 x 5]
##
## Population.x Population.y Name.x Name.y
## (int) (int) (chr) (chr)
## 1 27025 25000 Gibraltar Gibraltar
## 2 4017733 3567000 Singapore Singapore
## Variables not shown: LocalName (chr)
Задание 4 Узнайте, сколько крупных городов (city) на каждом континенте и сколько суммарно людей живет в городах. Ожидаемый результат:
inner_join(city_t,country_t,by="CountryCode") %>%
group_by(Continent) %>%
summarize(TotalCityPopulation=sum(Population.x),TotalCityCount=n())
## Source: local data frame [6 x 3]
##
## Continent TotalCityPopulation TotalCityCount
## (chr) (int) (int)
## 1 Africa 135838579 366
## 2 Asia 697604103 1766
## 3 Europe 241942813 841
## 4 North America 168250381 581
## 5 Oceania 13886149 55
## 6 South America 172037859 470
Задание 5 ВЫдайте 5 самых больших по населению столиц Европы
inner_join(city_t,country_t,by=c("CityID"="Capital")) %>%
filter(Continent=="Europe") %>%
arrange(desc(Population.x)) %>%
head(5)
## Source: local data frame [5 x 19]
##
## CityID Name.x CountryCode.x District Population.x CountryCode.y
## (int) (chr) (chr) (chr) (int) (chr)
## 1 3580 Moscow RUS Moscow (City) 8389200 RUS
## 2 456 London GBR England 7285000 GBR
## 3 3068 Berlin DEU Berliini 3386667 DEU
## 4 653 Madrid ESP Madrid 2879052 ESP
## 5 1464 Roma ITA Latium 2643581 ITA
## Variables not shown: Name.y (chr), Continent (chr), Region (chr),
## SurfaceArea (dbl), IndepYear (int), Population.y (int), LifeExpectancy
## (dbl), GNP (dbl), GNPOld (dbl), LocalName (chr), GovernmentForm (chr),
## HeadOfState (chr), Code2 (chr)
girls
## name age hobby height
## g1 Лена 19 лыжи 166.0
## g2 Жанна 22 вышивка 156.5
## g3 Даша 29 лыжи 180.0
## g4 Ира 26 танцы 170.0
## g5 Зина 16 танцы 160.0
boys
## name age hobby height
## b1 Гена 19 лыжи 188.0
## b2 Женя 32 мотоцикл 166.5
## b3 Саша 29 лыжи 180.0
## b4 Дима 26 танцы 170.0
inner_join(x=girls,y=boys,by="hobby")
## name.x age.x hobby height.x name.y age.y height.y
## 1 Лена 19 лыжи 166 Гена 19 188
## 2 Лена 19 лыжи 166 Саша 29 180
## 3 Даша 29 лыжи 180 Гена 19 188
## 4 Даша 29 лыжи 180 Саша 29 180
## 5 Ира 26 танцы 170 Дима 26 170
## 6 Зина 16 танцы 160 Дима 26 170
left_join(x=girls,y=boys,by="hobby")
## name.x age.x hobby height.x name.y age.y height.y
## 1 Лена 19 лыжи 166.0 Гена 19 188
## 2 Лена 19 лыжи 166.0 Саша 29 180
## 3 Жанна 22 вышивка 156.5 <NA> NA NA
## 4 Даша 29 лыжи 180.0 Гена 19 188
## 5 Даша 29 лыжи 180.0 Саша 29 180
## 6 Ира 26 танцы 170.0 Дима 26 170
## 7 Зина 16 танцы 160.0 Дима 26 170
right_join(x=girls,y=boys,by="hobby")
## name.x age.x hobby height.x name.y age.y height.y
## 1 Лена 19 лыжи 166 Гена 19 188.0
## 2 Даша 29 лыжи 180 Гена 19 188.0
## 3 <NA> NA мотоцикл NA Женя 32 166.5
## 4 Лена 19 лыжи 166 Саша 29 180.0
## 5 Даша 29 лыжи 180 Саша 29 180.0
## 6 Ира 26 танцы 170 Дима 26 170.0
## 7 Зина 16 танцы 160 Дима 26 170.0
full_join(x=girls,y=boys,by="hobby")
## name.x age.x hobby height.x name.y age.y height.y
## 1 Лена 19 лыжи 166.0 Гена 19 188.0
## 2 Лена 19 лыжи 166.0 Саша 29 180.0
## 3 Жанна 22 вышивка 156.5 <NA> NA NA
## 4 Даша 29 лыжи 180.0 Гена 19 188.0
## 5 Даша 29 лыжи 180.0 Саша 29 180.0
## 6 Ира 26 танцы 170.0 Дима 26 170.0
## 7 Зина 16 танцы 160.0 Дима 26 170.0
## 8 <NA> NA мотоцикл NA Женя 32 166.5
semi_join(x=girls,y=boys,by="hobby")
## name age hobby height
## 1 Лена 19 лыжи 166
## 2 Даша 29 лыжи 180
## 3 Ира 26 танцы 170
## 4 Зина 16 танцы 160
anti_join(x=girls,y=boys,by="hobby")
## name age hobby height
## 1 Жанна 22 вышивка 156.5
country_t %>%
filter(Continent=="Europe") %>%
select(Region) %>%
distinct()
## Source: local data frame [6 x 1]
##
## Region
## (chr)
## 1 Southern Europe
## 2 Western Europe
## 3 Eastern Europe
## 4 Nordic Countries
## 5 Baltic Countries
## 6 British Islands
country_t %>%
filter(!(Continent %in% c("Asia","Oceania")) & Population>1e8) %>%
select(Name, Population, Continent) %>%
arrange(Continent)
## Source: local data frame [4 x 3]
##
## Name Population Continent
## (chr) (int) (chr)
## 1 Nigeria 111506000 Africa
## 2 Russian Federation 146934000 Europe
## 3 United States 278357000 North America
## 4 Brazil 170115000 South America
country_t %>%
filter(!(Continent %in% c("Asia","Oceania")) , Population>1e8) %>%
select(Name, Population, Continent) %>%
arrange(Continent)
## Source: local data frame [4 x 3]
##
## Name Population Continent
## (chr) (int) (chr)
## 1 Nigeria 111506000 Africa
## 2 Russian Federation 146934000 Europe
## 3 United States 278357000 North America
## 4 Brazil 170115000 South America
country_t %>%
filter(Continent=="Europe") %>%
select(Name,Continent,SurfaceArea,Population) %>%
mutate(Density=Population/SurfaceArea) %>%
filter(Density<10) %>%
arrange(desc(Density))
## Source: local data frame [3 x 5]
##
## Name Continent SurfaceArea Population Density
## (chr) (chr) (dbl) (int) (dbl)
## 1 Russian Federation Europe 17075400 146934000 8.60501072
## 2 Iceland Europe 103000 279000 2.70873786
## 3 Svalbard and Jan Mayen Europe 62422 3200 0.05126398
country_t %>%
filter(Continent %in% c("Africa","Europe") & is.na(LifeExpectancy)) %>%
select(Name,Continent) %>%
arrange(Continent)
## Source: local data frame [3 x 2]
##
## Name Continent
## (chr) (chr)
## 1 British Indian Ocean Territory Africa
## 2 Svalbard and Jan Mayen Europe
## 3 Holy See (Vatican City State) Europe
filter(country_t,
grepl("Monarchy",GovernmentForm) &
!grepl("Constitutional",GovernmentForm)) %>%
select(Name,Continent,GovernmentForm,Population) %>%
arrange(desc(Population))
## Source: local data frame [9 x 4]
##
## Name Continent GovernmentForm Population
## (chr) (chr) (chr) (int)
## 1 Saudi Arabia Asia Monarchy 21607000
## 2 Oman Asia Monarchy (Sultanate) 2542000
## 3 Bhutan Asia Monarchy 2124000
## 4 Swaziland Africa Monarchy 1008000
## 5 Bahrain Asia Monarchy (Emirate) 617000
## 6 Qatar Asia Monarchy 599000
## 7 Brunei Asia Monarchy (Sultanate) 328000
## 8 Samoa Oceania Parlementary Monarchy 180000
## 9 Tonga Oceania Monarchy 99000