Concerning @jmcvw's comment, please see the homework FAQ
# fake data using numerics; datetime objects will differ
Inp <- data.frame(date = seq(1:100))
# pre-allocate vector
Out <- rep(NA, 100)
# as written the loop only cycles the number (length) of columns, not rows
for (i in 1:length(Inp)) Out[i] <- max(Inp$date[i]:Inp$date[i + 10]) -> a
a
#> [1] 11
# corrected for that, it overshoots the range of Inp
for (i in 1:nrow(Inp)) Out[i] <- max(Inp$date[i]:Inp$date[i + 10]) -> b
#> Error in Inp$date[i]:Inp$date[i + 10]: NA/NaN argument
b
#> [1] 100
Created on 2020-10-23 by the [reprex package]
(https://reprex.tidyverse.org) (v0.3.0.9001)
The for
statement is not the preferred approach for this class of problem in R
, which is a functional language as presented to the user: f(x) = y.
x is the given, in this case a numeric column of a data frame, which can be simplified to a numeric vector, Inp.
y is the desired output, in this case another numeric vector representing the maxima of each sub-sequence of 10 elements of x.
f is the object that transforms x to y.
We say that f is a function, x is an argument and y is a value or return value.
Everything in R
is an object, including functions, which can be arguments to other functions. Objects can be composed of other objects.
From that perspective, we have one piece in hand, max
, which takes as its argument a vector. Now, we need a function that will provide a vector that represents a window of x.
At this point a toy example
is helpful. Assume a x
Inp <- 1:10
and y that represents the maximum of each run of two elements. By inspection that's easy enough—it's simply the even integers. One of the possible ways of doing this is
Inp <- 1:10
Inp[which(Inp%%2 == 0)]
#> [1] 2 4 6 8 10
Created on 2020-10-23 by the reprex package (v0.3.0.9001)
This composition consists of the %%
modulus function (a so-called primitive), which
that finds even numbers (0 remainder) and the subset operators [
and ]
, primitives that filter for the elements that meet the modulus test.
Another way would be to split
the toy vector into the number of pieces desired.
Finally, take a look at slider for a set of functions designed to deal with this type of windowing problem.