解决'ts对象需至少一个观测值'错误,统计2016年各月推文量并绘图
解决
ts object must have one or more observations错误并统计2016年各月推文数量 问题背景
你遇到了ts object must have one or more observations(ts对象必须包含一个或多个观测值)的报错,目标是统计2016年每个月的推文数量并绘制图表,找出推文最多的月份。你的原始代码及数据结构截图如下:

原始代码:
library(ggplot2) library(RColorBrewer) library(rstudioapi) current_path = rstudioapi::getActiveDocumentContext()$path setwd(dirname(current_path )) print( getwd() ) donaldtrump <- read.csv("random_poll_tweets.csv", stringsAsFactors = FALSE) print(str(donaldtrump)) time8_ts <- ts(random$time8, start = c(2016,8), frequency = 12) time7_ts <- ts(random$time7, start = c(2016,7), frequency = 12) time6_ts <- ts(random$time6, start = c(2016,6), frequency = 12) time5_ts <- ts(random$time5, start = c(2016,5), frequency = 12) time4_ts <- ts(random$time4, start = c(2016,4), frequency = 12) time3_ts <- ts(random$time3, start = c(2016,3), frequency = 12) time2_ts <- ts(random$time2, start = c(2016,2), frequency = 12) time1_ts <- ts(random$time1, start = c(2016,1), frequency = 12) browser_mts <- cbind(time8_ts, time7_ts,time6_ts,time5_ts,time4_ts,time3_ts,time2_ts,time1_ts) dimnames(browser_mts)[[2]] <- c("8","7","6","5","4","3","2","1") pdf(file="fig_browser_tweet_R.pdf",width = 11,height = 8.5) ts.plot(browser_mts, ylab = "Amount of Tweet", xlab = "Month", plot.type = "single", col = 1:5) legend("topright", colnames(browser_mts), col = 1:5, lty = 1, cex=1.75)
错误原因分析
你的代码存在两个核心问题:
- 读入的数据对象是
donaldtrump,但后续创建ts对象时误用了未定义的random,导致读取空值生成无效ts对象; - 错误地将每个月份列单独转成ts再合并,这种方式不符合统计各月总推文量的需求,且若某列无数据就会触发
ts object must have one or more observations报错。
解决方案步骤
1. 数据预处理与月份提取
首先从数据中提取推文的发布月份(对应截图里的created_at字段),将其转换为日期格式后筛选2016年数据:
library(ggplot2) library(rstudioapi) # 设置工作路径 current_path = rstudioapi::getActiveDocumentContext()$path setwd(dirname(current_path )) # 读入数据 donaldtrump <- read.csv("random_poll_tweets.csv", stringsAsFactors = FALSE) # 处理日期列:转换为POSIXct格式,匹配Twitter默认时间格式 donaldtrump$created_at <- as.POSIXct(donaldtrump$created_at, format = "%a %b %d %H:%M:%S %z %Y") # 筛选2016年的推文数据 tweets_2016 <- subset(donaldtrump, format(created_at, "%Y") == "2016") # 提取月份(数字格式+英文缩写,方便后续排序和展示) tweets_2016$month <- as.integer(format(tweets_2016$created_at, "%m")) tweets_2016$month_name <- format(tweets_2016$created_at, "%b")
2. 统计各月推文数量
用两种方法实现分组统计:
方法1:Base R 原生统计
# 统计各月推文数 monthly_tweets <- table(tweets_2016$month) # 转换为数据框,重命名列 monthly_tweets_df <- as.data.frame(monthly_tweets) colnames(monthly_tweets_df) <- c("month", "count") # 按月份排序 monthly_tweets_df <- monthly_tweets_df[order(monthly_tweets_df$month), ] # 合并月份名称 monthly_tweets_df$month_name <- month.abb[monthly_tweets_df$month]
方法2:dplyr 简洁统计
library(dplyr) monthly_tweets_df <- tweets_2016 %>% group_by(month, month_name) %>% summarise(count = n(), .groups = "drop") %>% arrange(month) # 按1-12月顺序排序
3. 绘制图表找出推文最多的月份
推荐用柱状图直观对比各月数量,也可使用时间序列图:
柱状图(ggplot2)
pdf(file="fig_monthly_tweets_bar.pdf", width = 11, height = 8.5) ggplot(monthly_tweets_df, aes(x = factor(month_name, levels = month.abb), y = count)) + geom_bar(stat = "identity", fill = "#1DA1F2") + # Twitter蓝填充 labs(x = "2016年月份", y = "推文数量", title = "2016年各月推文数量统计") + geom_text(aes(label = count), vjust = -0.5, size = 4) + # 在柱子上方显示数值 theme_minimal() + theme(plot.title = element_text(hjust = 0.5)) # 标题居中 dev.off()
时间序列图(ts.plot)
若坚持使用ts对象绘图,需先补全无推文的月份(避免空值报错):
# 补全1-12月的完整数据,无推文的月份计数设为0 full_months <- data.frame(month = 1:12, month_name = month.abb) monthly_tweets_full <- merge(full_months, monthly_tweets_df, by = c("month", "month_name"), all.x = TRUE) monthly_tweets_full$count[is.na(monthly_tweets_full$count)] <- 0 # 创建合法的ts对象 tweets_ts <- ts(monthly_tweets_full$count, start = c(2016, 1), frequency = 12) pdf(file="fig_monthly_tweets_ts.pdf", width = 11, height = 8.5) ts.plot(tweets_ts, ylab = "推文数量", xlab = "月份", col = "#1DA1F2", lwd = 2) points(tweets_ts, pch = 16, col = "#1DA1F2") # 添加数据点 text(tweets_ts, labels = tweets_ts, pos = 3) # 显示数值标签 dev.off()
关键提示
- 如果你的日期格式与Twitter默认格式不同,需调整
as.POSIXct中的format参数,确保日期转换成功; - 补全无推文的月份是解决
ts object must have one or more observations报错的核心,保证ts对象包含12个完整的观测值; - 柱状图能最直观地对比各月推文数量,柱子最高的月份即为推文最多的月份。
内容的提问来源于stack exchange,提问作者Mastery mind
相关产品推荐
相关产品推荐

