平均值基于其他列的元素

时间:2013-05-15 11:29:15

标签: r dataframe

所以,我一直试图让这个工作,但由于某种原因,我只是没有在这方面取得任何进展。而且我希望你们能帮助我。差不多,我有一个数据框,我希望获得特定值范围的平均值,其中这些值来自同一数据框内的其他列,适用于每个用户。

所以,假设我有这个数据框。

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])
})

但问题是它没有使用toot值作为它的起始位置。以下是警告信息:

> 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

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

2 个答案:

答案 0 :(得分:3)

您可以使用by()执行此操作。像:

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

答案 1 :(得分:2)

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