user6678274
user6678274

Reputation: 53

How to make iterations over dates in R

This is a more general problem I get in R. Say I want to create a subset for a dataset data that contains the first 10 days the days 1,...,10. For a single day I can easy make the subset like this

data_new <- subset(data, data$time == as.Date(as.character(2016-01-01)) )

But say I want the first 10 days in January 2016. I try to make a loop like this

data_new <- matrix(ncol=2,nrow=1)
for(j in 1:10) {
    data_new[,j]= subset(data, data$time==as.Date(as.character(2016-01-j)))
}

but this code can not run in R because of the term as.character(2016-01-j).

How can I create such a subset?

Upvotes: 0

Views: 51

Answers (1)

lukeA
lukeA

Reputation: 54237

You could do

data_new = subset(data, data$time %in% as.Date(paste0("2016-01-", 1:10)))

Upvotes: 1

Related Questions