Sebastián Daza
2012-Feb-10 02:25 UTC
[R] calculations combining values from different rows
Hi everyone, I looking for functions or systematic ways to do calculations between different columns and rows in R, as one can do easily in Excel. For example, I have two variables, a and b, where a1 represents an a value in row 1, and b2 represents a b value in row 2, etc. a <- c(4,3,5,5,6,7,3,2,1,4) b <- c(2,4,1,2,5,3,1,8,7,5) data <- cbind(a,b) I have to calculate something like this: x1 = NA x2 = -b1 /24 * a1 + b2 /2 * a2 + b3 /24 * a3 x3 = -b2 /24 *a2 + b3 /2 * a3 + b4 /24 * a4 x4 = -b3 /24 *a3 + b4 /2 * a4 + b5 /24 * a5 ... x9 = -b8 /24* a8 + b9 /2 * a9 + b10 /24 * a10 x10= NA For example, x2 would be equal to: -2/24*4 +4/2*3 + 1/24 *5 Any ideas? Thank you in advance. -- Sebasti?n Daza
William Dunlap
2012-Feb-10 02:54 UTC
[R] calculations combining values from different rows
Is the following give the answer you want? It is a pretty literal transliteration of your idiom: > a <- c(4,3,5,5,6,7,3,2,1,4) > b <- c(2,4,1,2,5,3,1,8,7,5) > i <- seq(2, length(a)-1, by=1) > x <- rep(NA, length(a)) > x[i] <- -b[i-1]/24 * a[i-1] + b[i]/2 * a[i] + b[i+1]/24 * a[i+1] > print(x) [1] NA 5.875000 2.416667 6.041667 15.458333 9.375000 1.291667 8.166667 [9] 3.666667 NA The filter() function makes it easier to generalize > as.vector(filter(a*b, c(1/24, 1/2, -1/24), method="convolution")) [1] NA 5.875000 2.416667 6.041667 15.458333 9.375000 1.291667 8.166667 [9] 3.666667 NA (The as.vector is simply to get rid of the time-series-related attributes that filter sticks on its result.) Bill Dunlap Spotfire, TIBCO Software wdunlap tibco.com> -----Original Message----- > From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Sebasti?n Daza > Sent: Thursday, February 09, 2012 6:26 PM > To: r-help at r-project.org > Subject: [R] calculations combining values from different rows > > Hi everyone, > I looking for functions or systematic ways to do calculations between > different columns and rows in R, as one can do easily in Excel. For > example, I have two variables, a and b, where a1 represents an a value > in row 1, and b2 represents a b value in row 2, etc. > > a <- c(4,3,5,5,6,7,3,2,1,4) > b <- c(2,4,1,2,5,3,1,8,7,5) > data <- cbind(a,b) > > I have to calculate something like this: > > x1 = NA > x2 = -b1 /24 * a1 + b2 /2 * a2 + b3 /24 * a3 > x3 = -b2 /24 *a2 + b3 /2 * a3 + b4 /24 * a4 > x4 = -b3 /24 *a3 + b4 /2 * a4 + b5 /24 * a5 > ... > x9 = -b8 /24* a8 + b9 /2 * a9 + b10 /24 * a10 > x10= NA > > For example, x2 would be equal to: -2/24*4 +4/2*3 + 1/24 *5 > > Any ideas? > Thank you in advance. > > -- > Sebasti?n Daza > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code.