Más contenido relacionado
Similar a TokyoR58 初心者セッション (13)
TokyoR58 初心者セッション
- 21. 4.データの確認:概要
# 先頭からn行見る
head(iris, 2)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
15.1 3.5 1.4 0.2 setosa
24.9 3.0 1.4 0.2 setosa
# 基礎集計
summary(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. :4.30 Min. :2.000 Min. :1.000 Min. :0.100
setosa :50
1st Qu.:5.10 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
versicolor:50 Median :5.80 Median :3.000 Median :4.350
Median :1.300 virginica :50 Mean :5.843 Mean :3.057
Mean :3.758 Mean :1.199
3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
- 23. 4.データの確認:データ型
# データ型の変更
# data.tableにする
table_iris <- as.data.frame(iris)
# 確認
is.data.table(table_iris)
[1] TRUE
# 各カラムごとの型
# 文字型にする
table_iris$Sepal.Length <-
as.character(table_iris$Sepal.Length)
# 確認
is. character(table_iris$Sepal.Length)
[1] TRUE
- 26. 5.データの整理:列の追加、削除、選択
# id列とNo列を追加
iris1 <- iris%>%
mutate(id = paste0(“id”, 1:nrow(iris)),
No = 1:nrow(iris))
# No列を削除
iris2 <- iris1%>%
select(-No)
# 末尾がLengthのカラムと種名、id列を選択
iris3 <- iris2%>%
select(id, Species, ends_with("Length"))
- 28. 5.データの整理:条件抽出
# idが3より大きいデータを抽出
iris4 <- iris3%>%
filter(id > 3)
# end条件は &、or条件は | で指定
# Sepal.LengthとPetal.Lengthの両方が平均以上のデータを抽出
iris5 <- iris4%>%
filter(Sepal.Length >= mean(Sepal.Length) &
Petal.Length >= mean(Petal.Length))
# Sepal.LengthとPetal.Lengthのどちらかが平均以上のデータを抽
出
iris6 <- iris4%>%
filter(Sepal.Length >= mean(Sepal.Length) |
Petal.Length >= mean(Petal.Length))
- 29. 6.データの集計
# 種類ごとに長さの平均と分散を求める
summary_iris <- iris%>%
group_by(Species)%>%
summarise_at(vars(ends_with("Length")),
funs(mean, sd))
summary_iris
# A tibble: 3 x 5
Species Sepal.Length_mean Petal.Length_mean Sepal.Length_sd
Petal.Length_sd
<fctr> <dbl> <dbl> <dbl> <dbl>
setosa 5.006 1.462 0.3524897
0.1736640
versicolor 5.936 4.260 0.5161711
0.4699110
virginica 6.588 5.552 0.6358796
0.5518947