# Loops (problem)

#### maxhod

##### New Member
Hi,

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
Code:
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

Code:
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

P.S. Thanks trinker and bryangoodrich

PROBLEM SOLVED

Last edited:

#### trinker

##### ggplot2orBust
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]
Code:
some code
[/NOPARSE]

which produces:
Code:
some code

#### bryangoodrich

##### 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.

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

#### trinker

##### ggplot2orBust
Here's another approach:

Code:
x <- rnorm(100)
split(x, rep(1:5, each=20))

#### trinker

##### ggplot2orBust
By the way loops are not usually the way to go in R as you can tell from bryan and I's answers.