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

R语言使用tidyverse基于前一行值填充列的问题求解

基于tidyverse的迭代填充缺失值解决方案

你的原有写法未生效的核心原因是:mutate为向量化运算,默认读取的是原列的历史值,不会读取同一次计算中刚生成的上一行结果。你需要的迭代累积逻辑可以借助purrr包的accumulate2()函数实现,该函数支持将上一轮计算结果传入下一轮计算。

完整可运行代码

# 加载依赖包
library(tidyverse)

# 构造示例数据集
ex_tbl <- tibble(col1 = c(5, NA, NA, NA), col2 = c(1, 1.3, 0.8, 1.2))

# 按规则计算填充col1
output <- ex_tbl %>%
  mutate(
    col1 = accumulate2(
      .x = col1,
      .y = col2,
      .f = function(prev_col1, curr_col1, curr_col2) {
        # 保留初始非NA值,NA值按规则迭代计算
        if (!is.na(curr_col1)) return(curr_col1)
        ifelse(curr_col2 > 1, prev_col1 * curr_col2, prev_col1)
      }
    ) %>% as.numeric()
  )

运行结果

print(output)
#> # A tibble: 4 × 2
#>    col1  col2
#>   <dbl> <dbl>
#> 1   5     1  
#> 2   6.5   1.3
#> 3   6.5   0.8
#> 4   7.8   1.2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 04:54:06