Reputation: 3471
I have a dataframe with 358 rows
df <- data.frame(A=rnorm(358),B=rnorm(358))
and want to subset at these breaks:
breaks <- c(59,119,178,238,298)
resulting in six dataframes with
59, 60, 59, 60, 60, 60 rows.
(This is a result of a 6 x 60 sampling design, of which two samples have been lost.)
Is this possible?
Upvotes: 1
Views: 73
Reputation: 18657
If you fancy a primitive loop solution you can simply iterate through you desired row numbers, I understand that you are interested in subsetting this data frame by row numbers.
set.seed(1)
df <- data.frame(A=rnorm(358),B=rnorm(358))
## Added 1
breaks <- c(1, 59,119,178,238,298, 358)
listDFs <- vector("list", length(breaks) - 1)
for (i in 1:(length(breaks)-1)) {
# Take observations from this to that row
listDFs[[i]] <- df[breaks[i]:breaks[i+1],]
}
I reckon that suggestion provided in comments by @Frank is better:
n = c(59, 60, 59, 60, 60, 60); split(df, rep(seq_along(n), n))
Loop would make sense if you are you looking for a visually convenient way to do more things on the generated object.
> sapply(listDFs, dim)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 59 61 60 61 61 61
[2,] 2 2 2 2 2 2
Upvotes: 1