2017-05-04 69 views
1

我正在使用R 3.4.0和dplyr 0.5.0(我也使用R 3.3.3进行了测试,并且我有相同的错误)。dplyr group_by在变量上抛出错误不在函数中

过去我一直在使用这种类型的代码(甚至是昨天!),但由于某些原因,它今天会产生一个错误。

例如,我有5分钟的时间间隔的数据,我想总结15分钟。由于我不能group_by日期时间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)) 

,这里是错误,我有:

错误grouped_df_impl(数据,unname商(VAR),降): 列 'DatesRound'有不受支持的类:POSIXlt,POSIXt

我也尝试使用转换:

d$DatesRoundChar <- strftime(as.POSIXct(d$DatesRound)) 
d$DatesRoundChar <- sapply(d$DatesRound, as.character) 

但是我仍然有同样的错误。

有谁知道为什么它抛出一个错误,甚至没有在函数中的变量?我该如何解决它?

回答

2

POSIXlt类是创建在dplyr链的麻烦,因为它是一个不支持classdplyr

d %>% 
    group_by(DatesRoundChar) 

错误grouped_df_impl(数据,unname(乏),滴):柱 DatesRound:不支持类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

d$DatesRound <- as.POSIXct(round(as.double(d$Dates)/(15*60))* 
        (15*60),origin=(as.POSIXlt('1970-01-01'))) 

将其更改为POSIXct或者另一种选择是group_by

d %>% 
    select(-DatesRound) %>% 
    group_by(DatesRoundChar) %>% 
    summarise(total=sum(values)) 
+1

感谢您的回答之前删除 'DatesRound' 列。事实上,使用'as.POSIXct'工作得非常好,因为它允许以更少的代码完成我想要的工作。 –

相关问题