# 期間（年月）を指定した値の引き算でエラーになる場合の対処法

**URL:** <https://community-ja.exploratory.io/t/topic/2128>\
**Category:** 質問\
**Created:** [2026 年 6 月 12 日午前 5:13 UTC](https://community-ja.exploratory.io/t/topic/2128 "2026-06-12T05:13:40Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![Takato\_Shiroto](https://community-ja.exploratory.io/user_avatar/community-ja.exploratory.io/takato_shiroto/32/23_2.png) [@Takato\_Shiroto](https://community-ja.exploratory.io/u/Takato_Shiroto)\
**Post date:** [2026 年 6 月 12 日午前 5:13 UTC](https://community-ja.exploratory.io/t/topic/2128/1 "2026-06-12T05:13:40Z")

</div>

カスタムRコマンドでグループごとに「特定の年月の値の差」を計算しようとしたところ、一部のグループでmust be size 1, not 0 のエラーが発生した時の原因と対処法を紹介します。

例えば、グループごとに、`2025-04` と `2024-10` の測定値の差を求めるために以下のようなRスクリプトを使っていたとします。

```auto
group_by(`センサーID`) %>%
mutate(`測定値差(2025-04 minus 2024-10)` =
`測定値`[`測定年月` == "2025-04"] -
`測定値`[`測定年月` == "2024-10"]) %>%
ungroup()

```

これを実行した際に、以下のようなエラーが発生することがあります。

```auto
! `測定値差(2025-04 minus 2024-10)` must be size 1, not 0.
ℹ In group 4: `センサーID = "S004"`.

```

![image](http://community-ja.exploratory.io/images/transparent.png)

このエラーの原因は、エラーになったグループ（センサーID = “S004”）には、`測定年月 == "2025-04"` または `測定年月 == "2024-10"` に該当する行が存在しないことが原因です。

`[測定年月 == "2025-04"]` のような絞り込みの書き方は、該当する行が無いと「長さ0」の結果を返します。`mutate` はグループの各行に対して長さ1の値を期待するため、長さ0が返ると `must be size 1, not 0` というエラーになります。

特に、一部のグループだけ年月のデータが揃っていない場合に起こりやすいです。

対処法として、差分のを求める際の各値を `first()` で囲みます。

```auto
group_by(`センサーID`) %>%
mutate(`測定値差` =
first(`測定値`[`測定年月` == "2025-04"]) -
first(`測定値`[`測定年月` == "2024-10"])) %>%
ungroup()

```

![image](http://community-ja.exploratory.io/images/transparent.png)

`first()` は、該当する行が無いグループでは欠損値（NA）を返します。  
これにより値の長さが必ず1に保たれるため、データが揃っていないグループがあってもエラーにならず実行できます。
