[R] a faster and shorter way to perform calculations?
dxc13 at health.state.ny.us
Wed Aug 29 15:58:26 CEST 2007
This is a continuation from a previous posting of mine:
The following algorithm below is what I want to accomplish:
Z(xk) = Average(Yi, i belongs to Ik), where Ik contains all i such that for
each j, |Xi,j - xkj│≤ 2. Here, j = 1, 2 and i corresponds to the elements
in each X and/or xk
x1 x2 y
1 1 2
2 2 6
3 3 12
Now, consider a second data frame or matrix (xk):
In the end, there should be matrix or data frame with 3 columns, xk1, xk2,
and z (the result of the algorithm). Having any NA's as an answer is just
fine. Here is my code to get this to get this to work, it is lengthy and I
am looking for a way to cut it down and get the same results.
w1 <- outer(xk$xk1, data[,x1], function(y,z) abs(z-y))
w2 <- outer(xk$xk2, data[,x2], function(y,z) abs(z-y))
w1[w1 > d1] <- NA
w2[w2 > d2] <- NA
i1 <- ifelse(!is.na(w1),col(w1),NA)
i2 <- ifelse(!is.na(w2),col(w2),NA)
#NOW COMPARE i1 AND i2 BY ROWS...IF THEY HAVE A VALID NUMBER IN
#THE SAME POSITION (RxC) THEN EXTRACT THE Z-VALUE CORRESPONDING
#TO THE COLUMN NUMBER
all <- cbind(i1,i2)
Ik <- lapply(as.data.frame(t(all)), function(x)
zk <- unlist(lapply(Ik, mean, na.rm = TRUE))
z <- cbind(zk)
#FINAL DATA FRAME WILL CONSIST OF xk (XK1 and XK2), ZK
xk$z <- z
df <- as.data.frame(sapply(xk,rbind))
I hope my question makes sense and someone can help find a way to reduce the
amount of code here.
I have attached a text file with better numbers to try this with.
dxc13 http://www.nabble.com/file/p12387673/test.txt test.txt
View this message in context: http://www.nabble.com/a-faster-and-shorter-way-to-perform-calculations--tf4347973.html#a12387673
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help