通过一个关于太阳黑子数据的 tidyverse 时间序列示例,当我尝试以 10 年为增量绘制图表时收到以下错误消息,似乎无法识别在步骤 1 中创建的新日期变量,想知道这是否是格式问题。
错误:mutate()
列有问题decade
。我decade = f(date)
。x 下标越界
感谢任何帮助
# libraries
library(datasets)
library(tidyverse)
library(tsibble)
library(ggplot)
# Tidy the data
tidy_ts <- sunspots %>%
as_tsibble() %>% # Convert to timeseries tibble
mutate( # Create new variables
year = year(index), # Create a year column
month = month(index) # Create a month column
) %>%
select( # Select, reorder, rename vars
date = index, # Rename "index" to "date"
year, # Use "year" as second variable
month, # Use "month" as third variable
spots = value # Rename "value" as "spots"
) %>%
print() # Show data
view(tidy_ts)
# Graph the tidy data by decade
tidy_ts %>%
index_by( # By decade
decade = ~ floor_date(tidy_ts$date, years(10))
) %>%
summarise(mean_s = mean(spots)) %>% # Mean for decade
ggplot(aes(decade, mean_s)) + # Plot means
geom_point() + # Scatterplot
geom_smooth() + # Smoother
ylab("Sunspots: Mean by Decade") # Label