Loops (problem)


I am new to R and having problems with understanding loops in R.

basically what i want is the following

say i have a variable y with 100 observations

I want y1 = first 20 observations
y2 = second 20 obs
y3 = third 20 obs
and so on until y5

i know i can do that with
y1 <- c(y[1:20]) and y2 <- c(y[20:40]) etc
but i want to use loop as once i understand how to do this simple thing i can proceed further.

I did the following but keep getting error

df <- list()

for(i in seq(from=0, to=80, by=20)){
for(j in seq(from=20, to=100, by=20)){
for(k in 1:5){
df[k] <- data.frame(x=c(x[i:j]), y=c(y[i:j]))
Above is my code of two variables x and y.
i would not mind doing it for one variable and then i can always join them together later.

Any support is appreciated. Thank you, Max :D

P.S. Thanks trinker and bryangoodrich

Last edited:


When you're posting code, dataframes or computer output it's helpful to wrap this information in code tags by:
  1. either clicking the pound (#) sign icon or
  2. wrap with [NOPARSE]
    some code

which produces:
some code
For more see this (LINK)


Probably A Mammal
1. Add a variable using gl that classifies the first 20 obs, 2nd 20, and so on.
2. Use tapply on y, by that class variable from 1., and do whatever it is you want to do to y of that class as the function.

tapply(y, gl(...), some_function)