I have looked for an answer high and low. It seems so simple but I am struggling with getting anything to work.
Using R 3.0 in Win 7.
I am looking for a way to find the max value (row by row) for: the row of interest, the row before, and row after.
an example would look something like this:
x max
1 1 NA
2 7 7
3 3 7
4 4 5
5 5 5
I could do this with a loop but I would like to avoid that if possible. I have explored things similar to rowSums
and rollmean
but they do not quite fit the bill since I want a max for a row after it as well.
Any thoughts are greatly appreciated!!
You could use embed
and pmax
in base R for this.
d <- data.frame(x=c(1,7,3,4,5))
transform(d, max=c(NA, do.call(pmax, as.data.frame(embed(d$x, 3))), NA))
# x max
# 1 1 NA
# 2 7 7
# 3 3 7
# 4 4 5
# 5 5 NA
Here's an approach using dplyr's lead()
and lag()
functions:
library(dplyr)
d <- data.frame(x = c(1,7,3,4,5))
mutate(d, max = pmax(lead(x), x, lag(x)))
#> x max
#> 1 1 NA
#> 2 7 7
#> 3 3 7
#> 4 4 5
#> 5 5 NA
Assuming that you want to do this for a matrix, not for a vector(use rollapply for vectors), this is straightforward solution, probably not the best in terms of the speed:
library(Hmisc)
x <- matrix(runif(10), ncol=2)
rowMaxs <- apply(x, 1, max)
row3Maxs <- apply(cbind(rowMaxs,
Lag(rowMaxs, 1),
Lag(rowMaxs, -1)), 1, max)
cbind(x, row3Maxs)
however from the performance standpoint the following might be better:
row3Maxsc <- c(NA,
sapply(2:(length(rowMaxs)-1),
function(i)
max(rowMaxs[i], rowMaxs[i-1], rowMaxs[i+1])
),
NA)
cbind(x, row3Maxs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.