user6883405
user6883405

Reputation: 403

Reducing dataset size by one iteratively in R

I have a dataset that I'd like to keep reducing by 1 until a certain condition. I want all the datasets saved separately and merged into a list. For example manually I could do:

a<-mtcars[1:nrow(mtcars),]
b<-mtcars[2:nrow(mtcars),]
c<-mtcars[3:nrow(mtcars),]
d<-mtcars[4:nrow(mtcars),]
e<-mtcars[5:nrow(mtcars),]
f<-mtcars[6:nrow(mtcars),]
g<-mtcars[7:nrow(mtcars),]
h<-mtcars[8:nrow(mtcars),]
i<-mtcars[9:nrow(mtcars),]
j<-mtcars[10:nrow(mtcars),]

as.list(a,b,c,d,e,f,g,h,i,j)

Let's suppose that at the 10th row, some condition is met, such as a certain date. How could I do this iteratively? I've tried a for loop, but end up with only the last dataset as the output, not each incrementally smaller dataset.

Upvotes: 0

Views: 144

Answers (2)

Stephen Ewing
Stephen Ewing

Reputation: 48

You were on the right path with the for loop. If you're only getting the last one back the way you're creating your results frame is wrong.

dataList = list()
for (i in seq(1, 10)){
    dataList[[i]] = mtcars[i:nrow(mtcars),]
}

changed to match edit

Upvotes: 1

iod
iod

Reputation: 7592

Two things:

  1. no reason to repeat the n:nrow(mtcars), just pass -(1:i) as the rows index.

  2. to include a condition, you can use an ifelse with break().

For example, here is the for loop where the condition is that it will repeat this cycle 7 times:

  mc<-list()
  for(i in 1:nrow(mtcars)) ifelse(i==7,break(),mc[[i]]<-mtcars[-(1:i),])

Upvotes: 1

Related Questions