You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言如何用初始dbh加对应年份diam_growth填充dbh列NA值

树木胸径缺失值填充计算

你可以根据自己的使用习惯选择以下两种实现方案:

方案1:tidyverse 实现(可读性更高)

library(dplyr)

tree_growth_filled <- tree_growth %>%
  # 按树木tag分组,单独处理每棵树的数据
  group_by(tag) %>%
  mutate(
    # 提取当前树木2018年的初始胸径
    init_dbh = dbh[year == 2018],
    # 按规则填充dbh
    dbh = ifelse(
      year == 2018, 
      dbh, 
      init_dbh + cumsum(coalesce(diam_growth, 0))
    )
  ) %>%
  # 删除辅助计算的列
  select(-init_dbh) %>%
  ungroup()

计算结果预览

# A tibble: 12 × 4
     tag diam_growth   dbh  year
   <dbl>       <dbl> <dbl> <dbl>
 1     1         0.4  10.4  2020
 2     1         0.5  10.9  2021
 3     1        NA    10    2018
 4     2         0.7  15.7  2020
 5     2         0.8  16.5  2021
 6     2        NA    15    2018
 7     3         0.9   7.9  2020
 8     3         1     8.9  2021
 9     3        NA     7    2018
10     4         0.1  12.1  2020
11     4         0.2  12.3  2021
12     4        NA    12    2018

方案2:base R 实现(无需加载额外依赖包)

# 生成每棵树tag与2018年初始胸径的映射表
init_map <- with(tree_growth[tree_growth$year == 2018, ], setNames(dbh, tag))

# 按tag分组处理填充
tree_growth_filled <- do.call(
  rbind,
  lapply(split(tree_growth, tree_growth$tag), function(df) {
    init_val <- init_map[as.character(df$tag[1])]
    df$dbh[df$year != 2018] <- init_val + cumsum(ifelse(is.na(df$diam_growth), 0, df$diam_growth))[df$year != 2018]
    df
  })
)
rownames(tree_growth_filled) <- NULL

两种方案的计算结果完全一致,符合你描述的计算逻辑。

内容的提问来源于stack exchange,提问作者KNieder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 16:39:01