r - Averages based on elements from other columns -
so, i’ve been trying working reason, i’m not making progress on this. , hoping if guys me. pretty much, have data frame average of specific range of values, these values other columns within same data frame, each user.
so, let’s have data frame.
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 so, take average of values between 2 elements prior of toot element through toot element.
here's i'm looking for:
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 as see, user 1, user’s toot value 4, want take average of user’s 1 values @ 4th element , average 2 elements before it.
this have far (with many variations of , function):
a$deck<-ave(a$values,a$user,fun=function(x) { z<-a$toot y<-z-2 mean(x[y:z]) }) but problem it’s not using toot value it’s starting position. here warning messages:
> warning messages: 1: in y:z : numerical expression has 30 elements: first used 2: in y:z : numerical expression has 30 elements: first used error in mean(x[y:z]) : error in evaluating argument 'x' in selecting method function 'mean': error in x[y:z] : 0's may mixed negative subscripts anything welcomed , appreciated, thanks.
library(plyr) ddply(a,.(user),function(df) { df$deck <- mean(df$values[(df$toot[1]-2):df$toot[1]]) df })
Comments
Post a Comment