如何使用 R 将连续数据聚合成日常数据

How to aggregate continuous data into daily data with R

我在 rfacebook 的帮助下从 facebook 的 API 中提取了数据。我 运行 使用支持向量机将每条消息分类为正面或负面的情绪分析。

我现在的数据是这样的

fromID    fromName     Message     createdTime                 SVM Label

122233    Max Muster   great game  2014-12-28T20:57:04+0000            1
133425    Hilde Mash   hate it!    2014-12-28T23:54:12+0000            2
142233    Fred Ast     awesome     2014-12-29T22:37:08+0000            1
139425    Fred Fein    hate it!    2014-12-28T12:21:06+0000            2

我首先运行通过应用

将 createdTime 列转换为 xts 格式

df$createdTime = strptime(df$createdTime,format="%Y-%m-%dT%H:%M:%S%z")

然后我先尝试用

汇总每天的评论数
number = apply.daily(df, sum)

但是,这似乎不起作用。

数字只包含NA。

我尝试了其他几种方法,但没有用。

充其量我希望有一个数据框来计算我每天有多少个 1 和 2 SVM 标签。但是,我不确定该怎么做。

如有任何帮助,我们将不胜感激!

预先感谢您的帮助!

使用dplyr,你可以这样做:

library(dplyr)
df$Date <- as.Date(df$createdTime)
summary_df <- df %>% group_by(Date) %>% summarise(class1 = sum(SVMLabel == 1), class2 = sum(SVMLabel == 2))

或者,您也可以使用 table 命令并按如下方式转换为数据帧:

df$Date <- as.Date(df$createdTime)
summary_df <- as.data.frame(table(df$Date, df$SVMLabel))

我根本不知道 xts 包,所以我改用 POSIXct 格式。

假设您的数据框名为 "df":

df$Time = as.POSIXct(df$createdTime, format = "%Y-%m-%dT%H:%M:%S+0000")  
library(dplyr)  
df2 = df %>%   
  mutate(Day = as.POSIXct(trunc.POSIXt(Time, units = "days"))) %>%  
  group_by(Day, SVMLabel) %>%  
  summarise(Count = n())  

print(df2)

对于上面的数据,这给了我:

来源:本地数据框 [3 x 3] 团体:天 [?]

     Day       SVMLabel Count
  (time)          (int) (int)
1 2014-12-28        1     1
2 2014-12-28        2     2
3 2014-12-29        1     1

这对我来说很合适。