R Language (Сковорцов) / Анализ данных на языке R
.pdfboxplot(mpg ~ am, df, ylab = "MPG", main ="MPG and AM",
col = "green", cex.lab = 1.3, cex.axis = 1.3)
boxplot(df$mpg[df$am == "Auto"], df$mpg[df$am == "Manual"], ylab = "MPG", main ="MPG and AM",
col = "green", cex.lab = 1.3, cex.axis = 1.3)
plot(df$mpg, df$hp, xlab = "MPG", ylab ="HP" , main ="MPG and HP", pch = 22)
plot(~ mpg + hp, df)
Более интересные графики строятся при помощи сторонних пакетов. Одним из наиболее известных является пакет ggplot2. Структура графиков в ggplot практически идентична: ggplot (название_датафрейма, aes(данные по оси х, данные по оси у, заливка цветом или данными))+вид_диаграммы(заливка цветом или данными, подпись оси х, подпись оси у, наименование графика):
library(ggplot2)
ggplot(df, aes(x = mpg))+
geom_histogram(fill = "white", col = "black", binwidth = 2)+
xlab("Miles/(US) gallon")+ ylab("Count")+ ggtitle("MPG histogram")
ggplot(df, aes(x = mpg, fill = am))+ geom_dotplot()+
xlab("Miles/(US) gallon")+ ylab("Count")+
scale_fill_discrete(name="Transmission type")+ ggtitle("MPG dotplot")
ggplot(df, aes(x = mpg))+ geom_density(fill = "red")
ggplot(df, aes(x = mpg, fill = am))+ geom_density(alpha = 0.5)+ xlab("Miles/(US) gallon")+ ylab("Count")+
scale_fill_discrete(name="Transmission type")+ ggtitle("MPG density plot")
ggplot(df, aes(x = am, y = hp, fill = vs))+ geom_boxplot()+
xlab("Transmission type")+ ylab("Gross horsepower")+
scale_fill_discrete(name="Engine type")+ ggtitle("Gross horsepower and engine type")
ggplot(df, aes(x = mpg, y = hp, size = qsec))+ geom_point()+
xlab("Miles/(US) gallon")+ ylab("Gross horsepower")+
scale_size_continuous(name="1/4 mile time")+ ggtitle("Miles/(US) gallon and Gross horsepower")
my_plot <- ggplot(df, aes(x = mpg, y = hp, col = vs, size = qsec))+ geom_point()
my_plot2 <- ggplot(df, aes(x = am, y = hp, fill = vs))
my_plot2 + geom_boxplot()
Задание 4.1. При помощи функции aggregate рассчитайте стандартное отклонение переменной hp (лошадиные силы) и переменной disp (вместимости двигателя) у машин с автоматической и ручной коробкой передач.
Полученные результаты (результаты выполнения функции aggregate) сохраните в переменную descriptions_stat.
Задание 4.2. В переменной my_vector сохранен вектор с пропущенными значениями. Вам нужно создать новый вектор fixed_vector, в котором все пропущенные значения вектора vector будут заменены на среднее значение по имеющимся наблюдениям. Ниже небольшой код, который может создать случайный вектор (выборка из нормального распределения) с пропущенными значениями.
my_vector <- rnorm(30)
my_vector[sample(1:30, 10)] <- NA # на десять случайных позиций поместим NA
Задание 4.3. Используем знакомые нам данные mtcars.
Нужно построить scatterplot с помощью ggplot из ggplot2, по оси x которого будет mpg, по оси y - disp, а цветом отобразить переменную (hp).
Полученный график нужно сохранить в переменную plot1.
13. Функции семейства apply
# steps 2 - 3 for vs apply library(ggplot2)
data(diamonds)
str(diamonds)
min_size <- numeric(nrow(diamonds)) for (i in 1:nrow(diamonds)){
min_size[i] <- min(diamonds[i, 8:10])
}
min_size_2 <- apply(diamonds[, 8:10], 1, min)
# steps 4 and 7 apply function ?apply(array, margin, ...)
apply(X, MARGIN, FUN, ...)
d <- matrix(rnorm(30), nrow = 5)
apply(d, MARGIN = 1, FUN = sd) apply(d, MARGIN = 2, FUN = sd)
apply(mtcars, 2, sd) apply(mtcars, 1, sd)
s <- apply(d, MARGIN = 2, FUN = sd) range(1:10)
my_range <- apply(d, MARGIN = 2, FUN = range) my_range
# step 8 apply advanced outliers_count <- function(x){
otliers <- x[abs(x - mean(x)) > 2 * sd(x)] if (length(otliers) > 0){
return(otliers) } else {
return("There are no otliers")
}
}
iris_num <- iris[, 1:4]
iris_outliers <- apply(iris_num, 2, outliers_count) str(iris_outliers)
# step 2 apply(x, 1, mean, ...) head(airquality)
?airquality
apply(airquality, 2, mean, na.rm = T)
colMeans()
colSums()
rowMeans()
rowSums()
# step 3 set.seed(42)