Search code examples
rfor-looprollapply

How to create a temporary vector inside a for loop in R?


I am trying to create a simple for loop in R that should create a temporary subset vector from the main data vector and do subsequent calculations on the temporary vector. The following is my code:

count <- 0
window_size<-100

for (counter in 1:length(main_data_vector)-window_size) 
{
temp_window <-main_data_vector[counter:counter+window_size]
count = count+1
}

When I run the code, the counter stops at length(main_data_vector)-window_size (expectedly). But the length of the temp_window stays 1 (should be 100) and the count goes to the end of length(main_data_vector) (should have the same value as counter). I am not familiar with rollapply (online examples only show basic functions like sum and mean for it).

Can anyone please point to what I am doing wrong here ?

Thanks.


Solution

  • You should add round brackets for counter+window_size-1 and length(main_data_vector)-window_size+1, i.e.,

    for (counter in 1:(length(main_data_vector)-window_size+1)) 
    {
         temp_window <-main_data_vector[counter:(counter+window_size-1)]
    }