开始使用免费开始使用

生成每月平均值

虽然 to.period() 命令在很多情境下都很有用,但在这里,选取单行来代表整个月份可能并不合适。

更合理的做法是按月生成平均气温。为此,您需要手动使用 split()lapply 计算每月平均值,然后使用 as.xts() 生成新的 xts 对象。这个流程看似复杂,但您已经具备完成它的技能!

上一个练习中得到的子集 xts 对象 temps_xts_2 已预加载到您的工作区。还预加载了一个 index 对象,包含数据覆盖范围内每个月第一天的日期向量。

本练习是课程的一部分

案例研究:在 R 中分析城市时间序列数据

查看课程

练习说明

  • 使用 split()temps_xts_2 对象的 mean 列生成按月的列表。请将周期(参数 f)指定为 "months"
  • 使用 lapply() 计算"均值的均值",即每个月的平均 mean 气温。
  • 使用 as.xts() 生成一个新的 xts 对象,包含 2010 至 2015 年波士顿的每月平均气温。为此,您需要将每月的 mean_of_means 数据与每月的 index 对象组合起来。
  • 最后,确认新的 temps_monthly 对象与 flights_xts 的时长与周期性一致。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Split temps_xts_2 into separate lists per month
monthly_split <- split(___$___ , f = "___")

# Use lapply to generate the monthly mean of mean temperatures
mean_of_means <- lapply(___, FUN = ___)

# Use as.xts to generate an xts object of average monthly temperature data
temps_monthly <- as.xts(as.numeric(___), order.by = ___)
 
# Compare the periodicity and duration of your new temps_monthly and flights_xts 
periodicity(___)
periodicity(___)
编辑并运行代码