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

如何在R中结合for loop与mutate()计算WorldPhones数据集年度电话增长量

解决方法:结合for循环与mutate()计算年度增长量

先梳理你现有代码的几个问题:

  • 代码中引用的sa_df未定义,应该替换为你已经生成的WPSumByYear
  • 增长量计算逻辑可能倒置:通常年度增长额是当期值 - 上期值,你写的WPSumByYear$Phones[i-1]- WPSumByYear$Phones[i]会得到负数结果,需根据需求调整

以下是完全符合作业要求(for loop + mutate())的实现方案:

步骤1:修正数据预处理细节

先把字符型的Year转为数值型并按顺序排序,避免循环时年份顺序混乱:

library(tidyverse)
WorldPhones <- datasets::WorldPhones

WorldPhones_df <- as.data.frame(WorldPhones) %>%
  mutate(Year = rownames(.)) %>%
  gather(key = "Region", value = "Phones", 1:7)

WPSumByYear <- WorldPhones_df %>%
  group_by(Year) %>%
  summarise(Phones = sum(Phones)) %>%  # 给汇总列明确命名,方便后续调用
  mutate(Year = as.numeric(Year)) %>%
  arrange(Year)

步骤2:用mutate()+for循环计算增长量

先通过mutate()初始化增长列,再用for循环逐行计算填充:

# 初始化growth列,第一个年份无前置数据,增长量设为0
WPSumByYear <- WPSumByYear %>% mutate(growth = 0)

# 从第2行开始循环计算年度增长额
for (i in 2:nrow(WPSumByYear)) {
  WPSumByYear$growth[i] <- WPSumByYear$Phones[i] - WPSumByYear$Phones[i-1]
}

完整可运行代码

library(tidyverse)
WorldPhones <- datasets::WorldPhones

WorldPhones_df <- as.data.frame(WorldPhones) %>%
  mutate(Year = rownames(.)) %>%
  gather(key = "Region", value = "Phones", 1:7)

WPSumByYear <- WorldPhones_df %>%
  group_by(Year) %>%
  summarise(Phones = sum(Phones)) %>%
  mutate(Year = as.numeric(Year)) %>%
  arrange(Year) %>%
  mutate(growth = 0)

# 循环计算增长量
for (i in 2:nrow(WPSumByYear)) {
  WPSumByYear$growth[i] <- WPSumByYear$Phones[i] - WPSumByYear$Phones[i-1]
}

# 查看结果
WPSumByYear

可选调整:计算增长率

如果作业要求的是年度增长率而非增长额,只需修改循环内的计算逻辑:

WPSumByYear$growth[i] <- (WPSumByYear$Phones[i] - WPSumByYear$Phones[i-1]) / WPSumByYear$Phones[i-1]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 03:27:53