Hello, probably this isn't hard, but I can't get R to do this. Thanks for your help! Assume I have a matrix of two covariates: n <- 1000 Y <- runif(n) X <- runif(n,min=0,max=100) data <- cbind(Y,X) Now, I would like to compute the local average of Y for each X interval 0-1, 1-2, 2-3, ... 99-100. In other words, I would like to obtain 100 (local) Ybars, one for each X interval with width 1. Also, I would like to do the same but instead of local means of Y obtain local medians of Y for each X interval. Best, Jens
local average
3 messages · jhainm@fas.harvard.edu, Zhen Pang, Rich FitzJohn
a<-sapply(1:100,function(x)mean(Y[X<x & X>x-1])) b<-sapply(1:100,function(x)median(Y[X<x & X>x-1]))
From: "Jens Hainmueller" <jens_hainmueller at ksg05.harvard.edu> To: "R-Help" <r-help at stat.math.ethz.ch> Subject: [R] local average Date: Wed, 20 Apr 2005 23:43:41 -0400 Hello, probably this isn't hard, but I can't get R to do this. Thanks for your help! Assume I have a matrix of two covariates: n <- 1000 Y <- runif(n) X <- runif(n,min=0,max=100) data <- cbind(Y,X) Now, I would like to compute the local average of Y for each X interval 0-1, 1-2, 2-3, ... 99-100. In other words, I would like to obtain 100 (local) Ybars, one for each X interval with width 1. Also, I would like to do the same but instead of local means of Y obtain local medians of Y for each X interval. Best, Jens
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Hi, cut() and tapply() are your friends: tapply(Y, cut(X, 0:100, include.lowest=TRUE), mean) To compute medians, just pass median to tapply(). You will get NAs where no data is found in any bin. Cheers, Rich
On 4/21/05, Jens Hainmueller <jens_hainmueller at ksg05.harvard.edu> wrote:
Hello, probably this isn't hard, but I can't get R to do this. Thanks for your help! Assume I have a matrix of two covariates: n <- 1000 Y <- runif(n) X <- runif(n,min=0,max=100) data <- cbind(Y,X) Now, I would like to compute the local average of Y for each X interval 0-1, 1-2, 2-3, ... 99-100. In other words, I would like to obtain 100 (local) Ybars, one for each X interval with width 1. Also, I would like to do the same but instead of local means of Y obtain local medians of Y for each X interval. Best, Jens
______________________________________________ R-help at stat.math.ethz.ch mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Rich FitzJohn rich.fitzjohn <at> gmail.com | http://homepages.paradise.net.nz/richa183 You are in a maze of twisty little functions, all alike