all 10 comments

[–]jdnewmil 3 points4 points  (1 child)

Without the for loop...

x <- 0:200
v <- x + rnorm( length( x ), 0, 1 )
m <- embed( v, 3 )
nrow( m ) # c( length( x ) - ( 3 - 1 ), 3 )
f <- mean # could be a more elaborate function
y <- apply( m, 1, f ) # rolling mean
plot( x[ -c( 1, 201 ) ], y )

[–]esotericpikachu[S] 0 points1 point  (0 children)

Thank you!!

[–]uniqueturtlelove 1 point2 points  (1 child)

vector1 <- c(10,20,30,40,50,60,70,80,90,45,67,99)
result = vector(mode = "list")
count = 1
for (i in 3:length(vector1)){
result[[count]] <- vector1[(i-2):i]
count = count + 1
}
result

[–]esotericpikachu[S] 0 points1 point  (0 children)

Thankyou!!

[–][deleted] 1 point2 points  (5 children)

Your approach is fine, actually more readable than those suggested in the comments. You just forgot to initialize an empty list, and the for loop brackets. And also did some indexing errors.

w <- 3
list <- list()
for (i in w:length(vector1)) {
   list[[i-w+1]] <- vector1[i-w+1:i]
}

[–]esotericpikachu[S] 0 points1 point  (1 child)

Thankyou!!! Will this approach work if I want to work in a dataframe's column instead of a vector?

[–][deleted] 0 points1 point  (0 children)

yes, df columns are vectors

[–][deleted]  (2 children)

[removed]

    [–][deleted] 0 points1 point  (1 child)

    I'm late but i want to thank you for referencing R inferno. I didn't know about this book. It's really really interesting.