Bài THực Hành Tuần 2

data("iris")
lnqt <- iris
str(lnqt)
## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
names(lnqt) <- c('SL','SW','PL','PW','S')
notsetosa <- iris[!iris$Species == 'setosa',"Sepal.Length" > 5]
summary(iris$Sepal.Length)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##   4.300   5.100   5.800   5.843   6.400   7.900
iris$lcoded <- cut(iris$Sepal.Length, breaks = c(4.3,4.8,7.2,7.9),labels = c('ngắn','vừa','dài'))
table(iris$lcoded)
## 
## ngắn  vừa  dài 
##   15  126    8
mean(iris$Sepal.Length)
## [1] 5.843333
var(iris$Sepal.Length)
## [1] 0.6856935
sd(iris$Sepal.Length)
## [1] 0.8280661
sum(iris$Sepal.Length)
## [1] 876.5
quantile(iris$Sepal.Length, .3)
##  30% 
## 5.27
aggregate(iris$Sepal.Length,list(iris$Species), FUN = 'summary')
##      Group.1 x.Min. x.1st Qu. x.Median x.Mean x.3rd Qu. x.Max.
## 1     setosa  4.300     4.800    5.000  5.006     5.200  5.800
## 2 versicolor  4.900     5.600    5.900  5.936     6.300  7.000
## 3  virginica  4.900     6.225    6.500  6.588     6.900  7.900
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.2     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
iris %>% group_by(Species)
## # A tibble: 150 × 6
## # Groups:   Species [3]
##    Sepal.Length Sepal.Width Petal.Length Petal.Width Species lcoded
##           <dbl>       <dbl>        <dbl>       <dbl> <fct>   <fct> 
##  1          5.1         3.5          1.4         0.2 setosa  vừa   
##  2          4.9         3            1.4         0.2 setosa  vừa   
##  3          4.7         3.2          1.3         0.2 setosa  ngắn  
##  4          4.6         3.1          1.5         0.2 setosa  ngắn  
##  5          5           3.6          1.4         0.2 setosa  vừa   
##  6          5.4         3.9          1.7         0.4 setosa  vừa   
##  7          4.6         3.4          1.4         0.3 setosa  ngắn  
##  8          5           3.4          1.5         0.2 setosa  vừa   
##  9          4.4         2.9          1.4         0.2 setosa  ngắn  
## 10          4.9         3.1          1.5         0.1 setosa  vừa   
## # ℹ 140 more rows