r - 将一列中的值添加到另一列中的值
问题描述
我正在计算我测量的树木的新直径,方法是获取它们的初始直径(2018 年拍摄),然后加上 2020 年和 2021 年的直径增长厘米数(diam_growth)。这将填写列中的 NA “分贝”。这里有一些示例数据来帮助解释
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,依此类推。
解决方案
按'tag'分组,replace
'diam_growth'值NA
在'dbh'中通过添加来自'dbh'的非NA值的值
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
推荐阅读
- performance - Xamarin Forms:调用 ASP.NET (ASMX) Web 服务时性能非常慢
- javascript - 在反应功能组件上测试酶中的点击事件未通过
- javascript - 为什么我的比较没有产生预期的结果?
- javascript - 如何基于 JSON 响应动态创建折叠组件并传递参数在 React Native 上进行折叠主体
- android - Play商店Android-vitals上的android.view.InflateException异常
- php - 使用 PHP 在 HTML 邮件中发送图像
- r - 使用 data.table::fread() 读取 xlsx 文件,但选择工作表
- python - python:从字典中提取信息
- json - 如何在 React js 中使用 json 数据类型的 map 方法显示单个数据
- c++ - https:// 使用 QNetworkAccessManager 访问