Reputation: 73
The table below is a small part of a data set I want to use to make three boxplots of:
## No year month day hour PM2.5 PM10 SO2 NO2 CO O3 TEMP PRES
## 1 7345 2014 1 1 0 20.0 90.0 18.0 62.0 NA NA -1.5 1007.3
## 2 7346 2014 1 1 1 43.0 348.0 25.0 91.0 1100 1.0 -2.6 1006.9
## 3 7347 2014 1 1 2 79.0 423.0 41.0 103.0 1800 1.0 -3.0 1006.9
## 4 7348 2014 1 1 3 82.0 337.0 43.0 101.0 2100 1.0 -3.3 1006.4
## 5 7349 2014 1 1 4 124.0 594.0 59.0 130.0 2400 1.0 -2.7 1006.1
## 6 7350 2014 1 1 5 89.0 307.0 47.0 102.0 2500 1.0 -3.1 1006.6
## 7 7351 2014 1 1 6 59.0 161.0 45.0 91.0 1900 1.0 -2.6 1007.2
## 8 7352 2014 1 1 7 31.0 93.0 24.0 69.0 900 4.0 -2.9 1007.9
## 9 7353 2014 1 1 8 21.0 90.0 18.0 52.0 700 17.0 0.0 1008.8
## 10 7354 2014 1 1 9 38.0 142.0 25.0 87.0 1200 1.0 9.0 1009.6
I want to make three boxplots of the variable PM2.5 where all of them have the condition hour == 12 but one for each of the years 2014, 2015 and 2016. They also need to be on the same graph. This is what I've tried:
plots <- data.frame(box14 = subset(dat, hour == 12 & year == 2014)$PM2.5,
box15 = subset(dat, hour == 12 & year == 2015)$PM2.5,
box16 = subset(dat, hour == 12 & year == 2016)$PM2.5)
boxplot(plots)
I just get 'error in data.frame ... arguments implying a differing number of rows'. What should I change to get the boxplots I want?
Upvotes: 1
Views: 49
Reputation: 58
In base r:
filtered_data <- original_data[original_data$hour == 12 & original_data$year %in% c(2014,2015,2016),]
and then
boxplot(PM2.5~year,data=filtered_data)
Upvotes: 1
Reputation: 2105
Here's a pretty quick solution using dplyr
and ggplot2
:
library(dplyr)
library(ggplot2)
dat %>%
as_tibble() %>%
filter(hour == 12) %>%
filter(year %in% c(2014, 2015, 2016)) %>%
ggplot(aes(x=as.factor(year), y=PM2.5)) +
geom_boxplot()
Upvotes: 2