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,该用户的 toot 值为 4,因此我想在第 4 个元素处取用户 1 值的平均值,并将其与之前的 2 个元素取平均值。

这就是我到目前为止所拥有的(有很多变体和 by 函数):

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

任何事情都受到欢迎和赞赏,谢谢。

4

2 回答 2

3

你可以用by(). 喜欢:

do.call(rbind, by(a, a$user, function(x) { cbind(x,deck=mean(x$values[x$toot[1]:(x$toot[1]-2)])) }))
于 2013-05-15T11:44:58.930 回答
2
library(plyr)
ddply(a,.(user),function(df) {
       df$deck <- mean(df$values[(df$toot[1]-2):df$toot[1]]) 
       df
})
于 2013-05-15T11:45:01.083 回答