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

如何用dplyr计算tr(year)/(op(year)-op(year-1))比率?

解决方案

用dplyr的lag()函数就能轻松实现需求,直接上代码和步骤:

首先确保你的数据集是按年份升序排列的(你的数据已经满足),然后通过以下步骤计算:

# 先加载dplyr,没安装的话先运行 install.packages("dplyr")
library(dplyr)

# 假设你的数据集命名为df
df <- tibble(
  year = c("1984", "1985", "1986", "1987", "1988"),
  op = c(10, 55, 79, 78, 109),
  tr = c(39.1, 132, 69.3, 47.7, 77.0),
  cp = c(38.3, 77.1, 78.7, 74.1, 86.4)
)

# 核心计算逻辑
result <- df %>%
  # 用lag()获取上一年的op值
  mutate(
    op_prev_year = lag(op),
    op_diff = op - op_prev_year,
    ratio = tr / op_diff,
    year2 = year
  ) %>%
  # 过滤掉没有上一年数据的1984年
  filter(!is.na(op_diff)) %>%
  # 只保留需要的列
  select(year2, ratio)

# 查看结果
print(result)

运行后会得到你预期的输出:

# A tibble: 4 × 2
  year2 ratio
  <chr> <dbl>
1 1985   2.93
2 1986   2.89
3 1987 -47.7 
4 1988  -2.48

关键说明:

  • lag(op)会将op列的值向下偏移一行,这样每行就能匹配到上一年的op数据
  • op_diff = op - op_prev_year就是你需要的op(year)-op(year-1)差值
  • 最后过滤掉op_diff为NA的行(也就是1984年,因为没有上一年数据),只保留目标列即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:46:00