如何在R中按月/年对变量求和?

时间:2018-11-19 06:51:15

标签: r dplyr lubridate

library(dplyr)
library(plotly)
library(lubridate)

googlesearch <- read.csv("multiTimeline.csv", header = FALSE, stringsAsFactors = FALSE)

googlesearch2 <- googlesearch [-1, ]
googlesearch2 <- googlesearch2 [-1, ]
colnames(googlesearch2)[1] <- 'Date' 
colnames(googlesearch2)[2] <- 'NumberofSearch'

googlesearch2$Date <- as.Date(googlesearch2$Date) 
googlesearch2 <- googlesearch2 %>%
  filter(Date > "2015-01-04" & Date < "2018-05-27")

googlesearch3 <- googlesearch2 %>%
  transform(googlesearch2$Date, Date = as.Date(as.character(Date), "%Y-%m-%d"))
googlesearch3 <- googlesearch2 %>%  
  mutate(month = format(Date, "%m"), year = format(Date, "%Y")) %>%
  group_by(Date, yearMon = as.yearmon(Date, "%m-%d-%Y"))

googlesearch3$Date <- as.numeric(googlesearch3$NumberofSearch)

googlesearch3 <- googlesearch3 %>%  
  mutate(month = format(Date, "%m"), year = format(Date, "%Y")) %>%
  group_by(Date, yearMon = as.yearmon(Date, "%m-%d-%Y")) %>%
  summarise(NumberofSearch_sum = sum(NumberofSearch))

data <- tbl_df(googlesearch3)

data %>%
  group_by(yearMon) %>%
summarise(NumberofSearch_mon = sum(NumberofSearch))

我知道这很混乱。 我收到此错误,不知道为什么。添加示例代码。

Error in summarise_impl(.data, dots) : 
  Evaluation error: invalid 'type' (character) of argument.

1 个答案:

答案 0 :(得分:0)

由于缺少可重现的示例,请尝试将示例代码的最后一个代码块替换为:

library(hablar)

data %>%
  retype() %>%
  group_by(yearMon) %>%
  summarise(NumberofSearch_mon = sum(NumberofSearch))

也许可行:)