我正在使用 R 3.4.0 和 dplyr 0.5.0(我也使用 R 3.3.3 进行了测试,并且出现了相同的错误)。
我过去经常使用以下类型的代码(甚至是昨天!),但由于某些原因,它今天产生了错误。
例如,我有 5 分钟间隔的数据,我想将其汇总为 15 分钟。由于我无法 group_by
DateTime POSIXlt
,因此我将变量转换为字符。但是,当我应用 group_by
函数时,它会在原始 DateTime POSIXlt
变量上产生错误,即使我在函数中使用了字符变量。
这是一个可重现的示例:
z <- seq(ISOdatetime(2017,01,01, 00,00,00), ISOdatetime(2017,02,28,23,45,00), by="5 min")
q <- rnorm(16990, mean=120, sd=75)
d<- data.frame("Dates"=z, "values"=q)
# Round the time to the nearest 15min
d$DatesRound <- as.POSIXlt(round(as.double(d$Dates)/(15*60))*(15*60),origin=(as.POSIXlt('1970-01-01')))
# Transform into character
d$DatesRoundChar <- as.character(d$DatesRound)
d2 <-
d %>%
group_by(DatesRoundChar)%>%
summarise(total=sum(values))
这是我遇到的错误:
Error in grouped_df_impl(data, unname(vars), drop) : column 'DatesRound' has unsupported class : POSIXlt, POSIXt
我也尝试过使用以下方法进行转换:
d$DatesRoundChar <- strftime(as.POSIXct(d$DatesRound))
d$DatesRoundChar <- sapply(d$DatesRound, as.character)
但是我仍然有同样的错误。
有谁知道为什么它会对不在函数中的变量抛出错误?我该如何解决它?
最佳答案
POSIXlt
类在 dplyr
链中造成了麻烦,因为它是 dplyr
中不受支持的类
d %>%
group_by(DatesRoundChar)
Error in grouped_df_impl(data, unname(vars), drop) : Column
DatesRound
: unsupported class POSIXlt/POSIXt
traceback()
#14: stop(list(message = "Column `DatesRound`: unsupported class POSIXlt/POSIXt",
# call = grouped_df_impl(data, unname(vars), drop), cppstack = NULL))
#13: .Call("dplyr_grouped_df_impl", PACKAGE = "dplyr", data, symbols,
# drop)
#12: grouped_df_impl(data, unname(vars), drop)
#11: grouped_df(groups$data, groups$group_names)
#10: group_by.data.frame(., DatesRoundChar)
#9: group_by(., DatesRoundChar)
#8: function_list[[k]](value)
#7: withVisible(function_list[[k]](value))
#6: freduce(value, `_function_list`)
#5: `_fseq`(`_lhs`)
#4: eval(expr, envir, enclos)
#3: eval(quote(`_fseq`(`_lhs`)), env, env)
#2: withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
#1: d %>% group_by(DatesRoundChar)
<小时/>
相反,我们可以使用 as.POSIXct
将其更改为 POSIXct
d$DatesRound <- as.POSIXct(round(as.double(d$Dates)/(15*60))*
(15*60),origin=(as.POSIXlt('1970-01-01')))
或者另一种选择是删除 group_by
之前的“DatesRound”列
d %>%
select(-DatesRound) %>%
group_by(DatesRoundChar) %>%
summarise(total=sum(values))
关于r - dplyr group_by 对不在函数中的变量抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43781981/