2013-05-15 53 views
0

所以,我一直試圖讓這個工作,但由於某種原因,我只是沒有取得任何進展。我希望你們能幫助我。非常多,我有一個數據框,我希望爲每個用戶獲取特定值範圍的平均值,其中這些值來自同一數據框中的其他列。基於來自其他列的元素的平均值

所以,假設我有這個數據框。

a<-data.frame(user=c(rep(1,10),rep(2,10),rep(3,10)), 
values=c(1:30),toot=c(rep(4,10),rep(5,10),rep(3,10))) 

user values toot 
    1  1  4 
    1  2  4 
    1  3  4 
    1  4  4 
    1  5  4 
    1  6  4 
    1  7  4 
    1  8  4 
    1  9  4 
    1  10  4 
    2  11  5 
    2  12  5 
    2  13  5 
    2  14  5 
    2  15  5 
    2  16  5 
    2  17  5 
    2  18  5 
    2  19  5 
    2  20  5 
    3  21  3 
    3  22  3 
    3  23  3 
    3  24  3 
    3  25  3 
    3  26  3 
    3  27  3 
    3  28  3 
    3  29  3 
    3  30  3 

所以,我想要的是toot元素之前的toot元素之前的2個元素之間的值的平均值。

這裏就是我在尋找:

user values toot  deck 
    1  1  4  3 
    1  2  4  3 
    1  3  4  3 
    1  4  4  3 
    1  5  4  3 
    1  6  4  3 
    1  7  4  3 
    1  8  4  3 
    1  9  4  3 
    1  10  4  3 
    2  11  5  14 
    2  12  5  14 
    2  13  5  14 
    2  14  5  14 
    2  15  5  14 
    2  16  5  14 
    2  17  5  14 
    2  18  5  14 
    2  19  5  14 
    2  20  5  14 
    3  21  3  22 
    3  22  3  22 
    3  23  3  22 
    3  24  3  22 
    3  25  3  22 
    3  26  3  22 
    3  27  3  22 
    3  28  3  22 
    3  29  3  22 
    3  30  3  22 

正如你看到的,用戶1,用戶的嘟嘟值是4,所以我想利用用戶的1個值的平均值在第4元素平均它與之前的2個元素。

這是我迄今(有許多這樣的變化,並與由功能):

a$deck<-ave(a$values,a$user,FUN=function(x) 
{ 
    z<-a$toot 
    y<-z-2 
mean(x[y:z]) 
}) 

但問題是,因爲它的起始位置它不使用嘟嘟值。以下是警告消息:

> Warning messages: 
1: In y:z : numerical expression has 30 elements: only the first used 
2: In y:z : numerical expression has 30 elements: only the first used 
Error in mean(x[y:z]) : 
error in evaluating the argument 'x' in selecting a method for function 'mean': Error in x[y:z] : only 0's may be mixed with negative subscripts 

任何事情都歡迎和讚賞,謝謝。

+0

警告即將到來,因爲'$一個是toot'不是標。即使使用'$ toot [1]',我也無法使其工作,但這只是因爲'ave'對我來說是一種外部功能。我經常看到'by'(在@ Rcoster的解決方案中)。 – Frank

+2

我記得嘗試過($ toot [1]),它適用於第一個用戶,但它也會將同樣的值應用於其他用戶。因此,第一個嘟嘟的值將應用於所有用戶,我不能這樣做,因爲每個用戶都有不同的起始值。 感謝您對此問題的調試。 – rj2700

回答

2
library(plyr) 
ddply(a,.(user),function(df) { 
     df$deck <- mean(df$values[(df$toot[1]-2):df$toot[1]]) 
     df 
}) 
+0

非常感謝!這工作。 – rj2700

3

您可以使用by()來完成。像:

do.call(rbind, by(a, a$user, function(x) { cbind(x,deck=mean(x$values[x$toot[1]:(x$toot[1]-2)])) })) 
+0

非常感謝!這工作。 – rj2700