r - Average over specific number of rows, according to criteria -


my data structured follows:

set.seed(20) rawdata <- data.frame(trial = c(rep(1, 10), rep(2, 10)),                         x_velocity = runif(20, 1, 3),                          y_velocity = runif(20, 4, 6)) 

i wish calculate average x_velocity , y_velocity across every 2 rows, each trial. anticipated output, first 4 rows be:

x_velocity_avg       y_velocity_avg na                   na 2.6460545            4.522224 na                   na 1.8081265            4.5175165 

how complete this?

you using function f in average of every 2 elements computed:

f <- function(a) tapply(a, rep(1:(length(a)/2), each = 2), fun = mean)  res <- data.frame(x_velocity_avg=rep(na, nrow(rawdata)),                    y_velocity_avg=rep(na, nrow(rawdata))) res$x_velocity_avg[c(f,t)] <- f(rawdata$x_velocity) res$y_velocity_avg[c(f,t)] <- f(rawdata$y_velocity)     # x_velocity_avg y_velocity_avg # 1              na             na # 2        2.646055       4.522224 # 3              na             na # 4        1.808127       4.517517 # 5              na             na # 6        2.943262       4.334551 # 7              na             na # 8        1.162082       5.899396 # 9              na             na # 10       1.697668       4.739195 # 11             na             na # 12       2.473324       4.778723 # 13             na             na # 14       1.744730       5.020097 # 15             na             na # 16       1.644518       4.986245 # 17             na             na # 18       1.431219       5.375815 # 19             na             na # 20       2.108719       4.909284 

Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -