![](/img/trans.png)
[英]Adding values from one column to another with missing values in the second column using R
[英]Adding values from one column to values in another
我正在計算我測量的樹木的新直徑,方法是獲取它們的初始直徑(2018 年拍攝),然后加上 2020 年和 2021 年的直徑增長厘米數 (diam_growth)。這將填寫列中的 NA “dbh”。 這里有一些示例數據可以幫助解釋
tag <- c(1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4)
diam_growth <- c(0.4, 0.5, NA, 0.7, 0.8, NA, 0.9, 1.0, NA, 0.1, 0.2, NA)
dbh <- c(NA, NA, 10, NA, NA, 15, NA, NA, 7, NA, NA, 12)
year <- c(2020, 2021, 2018, 2020, 2021, 2018, 2020, 2021, 2018, 2020, 2021, 2018)
tree_growth <- data.frame(tag, diam_growth, dbh, year)
tag diam_growth dbh year
1 1 0.4 NA 2020
2 1 0.5 NA 2021
3 1 NA 10 2018
4 2 0.7 NA 2020
5 2 0.8 NA 2021
6 2 NA 15 2018
7 3 0.9 NA 2020
8 3 1.0 NA 2021
9 3 NA 7 2018
10 4 0.1 NA 2020
11 4 0.2 NA 2021
12 4 NA 12 2018
因此,例如,對於標簽 1,代碼將采用 2018 年的 dbh (10) 並為 2020 年添加 0.4,為 2021 年添加 0.5。然后對於標簽 2,它將分別為 2020 年和 2021 年的初始 DBH 15 添加 0.7 和 0.8依此類推每個標簽 ID。
按“標簽”分組,通過將值與“dbh”中的非 NA 值相加, replace
“dbh”中為NA
的“diam_growth”值
library(dplyr)
tree_growth %>%
group_by(tag) %>%
mutate(diam_growth = replace(diam_growth, is.na(dbh),
diam_growth[is.na(dbh)] + dbh[!is.na(dbh)])) %>%
ungroup
-輸出
# A tibble: 12 × 4
tag diam_growth dbh year
<dbl> <dbl> <dbl> <dbl>
1 1 10.4 NA 2020
2 1 10.5 NA 2021
3 1 NA 10 2018
4 2 15.7 NA 2020
5 2 15.8 NA 2021
6 2 NA 15 2018
7 3 7.9 NA 2020
8 3 8 NA 2021
9 3 NA 7 2018
10 4 12.1 NA 2020
11 4 12.2 NA 2021
12 4 NA 12 2018
或者使用case_when
tree_growth %>%
group_by(tag) %>%
mutate(diam_growth = case_when(is.na(dbh) ~ diam_growth +
dbh[!is.na(dbh)], TRUE ~ diam_growth)) %>%
ungroup
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.