LoginSignup
0
1

More than 5 years have passed since last update.

[R言語]欠損のあるデータのサマリーをとる

Posted at

概要

欠損している行を含むデータに対して欠損している行を無視して平均を計算する

手順

以下のようなある観測所で観測された10年分の月ごとの合計降水量(mm)のCSVファイルを使用します。

year month total_precipitation
2009 1 176.5
2009 2 80.5
2009 3 207
2009 4 81.5
2009 5 130.5
2009 6 301.5
2009 7 136
2009 8 25.5
2009 9 70.5
2009 10 439.5
2009 11 263
2009 12 87
2010 1 72
2010 2 118
2010 3 147
2010 4 292.5
2010 5 146.5
2010 6 316.5
... ... ...
2018 7 143.5
2018 8 537
2018 9 236
2018 10
2018 11
2018 12
  • year:観測された年
  • month:観測された月
  • total_precipitation:月ごとの合計降水量(mm)

上記のようなCSVファイルをR言語で処理して月ごとの平均を求めます。

na_summarise
> data %>%
+   group_by(month) %>%
+   summarise(mean = mean(total_precipitation))
# A tibble: 12 x 2
   month  mean
   <int> <dbl>
 1     1   NA 
 2     2  119.
 3     3  129.
 4     4  165.
 5     5  251.
 6     6  373.
 7     7  170.
 8     8  227.
 9     9  228.
10    10   NA 
11    11   NA 
12    12   NA 

1月、10月、11月、12月のNAとなってしまいました。
これはその月のデータに少なくとも1件の欠損データを含むため、平均を計算できなかったことを表します。

そこで、以下のfilterで欠損している年と月を抽出します。

na_filter
> data %>%
+   filter(is.na(total_precipitation))
  year month total_precipitation
1 2015    12                  NA
2 2016     1                  NA
3 2018    10                  NA
4 2018    11                  NA
5 2018    12                  NA

2015/12、2016/1、2018/10、2018/11、2018/12のデータが欠損していることがわかりました。

この5行分のデータを無視して平均を計算するには、上と同様にfilterを使用してNAでない行だけを抽出して計算します。ただし、今回は NAでない 行だけを抽出したいため、filterの条件は逆になります。

non_na_summarise
> data %>%
+   filter(!is.na(total_precipitation)) %>%
+   group_by(month) %>%
+   summarise(mean = mean(total_precipitation))
# A tibble: 12 x 2
   month  mean
   <int> <dbl>
 1     1  102.
 2     2  119.
 3     3  129.
 4     4  165.
 5     5  251.
 6     6  373.
 7     7  170.
 8     8  227.
 9     9  228.
10    10  257.
11    11  164.
12    12  102.

事前にNAでない行を抽出することで平均がNAだった月が計算できていることがわかります。

合計についても同様に計算可能ですが、NAの行を除外しているため除外された行を含む月のデータは母数が他より少なくなっていることに注意が必要です。例えば12月のデータは2015年と2018年の分のデータが欠損しているため、8年分のデータの合計になっています。

non_na_sum
> data %>%
+   filter(!is.na(total_precipitation)) %>%
+   group_by(month) %>%
+   summarise(sum = sum(total_precipitation))
# A tibble: 12 x 2
   month   sum
   <int> <dbl>
 1     1  914  # 9年分
 2     2 1186.
 3     3 1294.
 4     4 1654.
 5     5 2514.
 6     6 3729 
 7     7 1704.
 8     8 2269 
 9     9 2280.
10    10 2312  # 9年分
11    11 1473  # 9年分
12    12  820  # 8年分

備考

今回使用したデータは以下のサイトでダウンロードしました。

気象庁|過去の気象データ・ダウンロード
https://www.data.jma.go.jp/gmd/risk/obsdl/index.php

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1