I am trying to find the max of rows 2:5, then 3:6, then 4:7 and so on for nrows(df). I am however having a problem thinking of how to do this because I have never used a for loop in the past successfully. Any help is greatly appreciated.

structure(c(76.89, 77.08, 77.05, 77.28, 77.28, 77.61, 77.03, 
77.61, 77.28, 77.3, 77.37, 77.61, 76.7, 77, 76.98, 77.09, 77.21, 
77.5, 76.74, 77.49, 76.98, 77.2, 77.29, 77.58, NA, 76.91, 77.27, 
77.13, 77.24, 77.45, NA, 0.910154726303475, 0.0129416332341208, 
0.220407104887854, 0.168306576903153, 0.20658489347966, NA, 0.117019893381879, 
-0.3753073637893, -0.0518604952677195, -0.0388399792853642, 0.0645577792123914
), .indexCLASS = "Date", .indexTZ = "UTC", tclass = "Date", tzone = "UTC", class =  c("xts", 
"zoo"), index = structure(c(631324800, 631411200, 631497600, 
631756800, 631843200, 631929600), tzone = "UTC", tclass = "Date"), .Dim = 6:7, .Dimnames = list(
NULL, c("open", "high", "low", "close", "avgco", "percenthigh", 
"percentlow")))

Specifically I want to apply the max function over the AD1$high column for rows 2 through 5 then rows 3 through 6 and so on and have this in a new column.

Thank You

有帮助吗?

解决方案 2

Using the zoo function "rollapply" solved my problem.

其他提示

You could do it by making three copies of your column (i.e "high") and offsetting them so one starts ahead one value and one starts behind one value. Then just take the max as you iterate across them:

y <- yourdata

t <- y[,"high"]
tback <- t[2:length(t)]
tforward <- append(NA,t)

using a loop

for(i in 1:length(t)) {
    maxvals[i] <- max(c(t[i],tback[i],tforward[i]), na.rm=T)
}

output

> maxvals
[1] 77.61 77.61 77.61 77.37 77.61 77.61

Or you could do it more efficiently without a loop by initializing maxvals to the proper length and filling its values.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top