2
我很難弄清楚爲什麼我的dplyr函數被轟炸了。當我運行默認n = 2的mutate_each時,它可以工作。它不適用於n = 1或n = 3。dplyr:`group_by`和`mutate_each`錯誤
library(dplyr)
## moving average function
get.mavg <- function(mycol, n=2) {
require(zoo)
mycol <- na.locf(mycol, na.rm=FALSE)
if(length(mycol) < n)
return(mycol)
c(mycol[1:(n-1)], rollapply(mycol, width=n, mean, align="right"))
}
dummy <- data_frame(Name1=c("A","A","A","A","B","B","B"),
Name2=c("B","B","C","C","C","C","C"),
stat = c(0,5,5,10, 10,5,5),
day = c(1:4, 1:3))
dummy %>%
group_by(Name2) %>%
mutate_each(funs(get.mavg(.,3)), stat:day)
Error: incompatible types, expecting a integer vector
如果我試圖通過單獨列到我的移動平均函數,它的工作原理!
get.mavg(dummy[dummy$Name2=="B",]$stat, 3)
# [1] 0 5
get.mavg(dummy[dummy$Name2=="C",]$stat, 3)
# [1] 5.000000 10.000000 8.333333 8.333333 6.666667
發生了什麼事?
雖然這並不等於你擁有它可能是你真正想要的是:'dummy%>%group_by(Name2)%>%mutate_each(funs(rollapplyr(。,3,mean,partial = TRUE)),stat:day)'。 'partial = TRUE'參數會導致在開始時採取部分方法,即輸出變爲c(mean(x [1]),mean(x [1:2]),mean(x [1:3] ),mean(x [2:4]),...,mean(x [(n-2):n]))'還要注意在rollapplyr結尾處的r。 –