2017-05-04 57 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'工作得非常好,因爲它允許以更少的代碼完成我想要的工作。 –