Created
March 19, 2015 08:44
-
-
Save micstr/eaea1524d23b7f9ef3be to your computer and use it in GitHub Desktop.
Looping through dates in R - examples of issues with indexing with dates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# examples of issues with indexing with dates for will turn to number | |
# Solution | |
# - DONT use dates as elements of your index | |
# - DO index alonmg length of your date list | |
library(data.table) | |
date.list <- c(as.Date("2015/3/1"), as.Date("2015/3/2")) | |
# 1 loop through dates? | |
for (i.date in unique(date.list)){ | |
str(i.date) | |
} | |
# Fail. You will see index i.date is number :( | |
for (i.date in date.list){ | |
# str(i.date) | |
print(paste0(i.date, ":", is.numeric(i.date))) | |
} | |
# 2 try as factors | |
for (i.date in as.factor(date.list)){ | |
str(i.date) | |
print(paste0(i.date, ":", is.numeric(i.date))) | |
} | |
# https://stat.ethz.ch/pipermail/r-help/2008-December/182516.html | |
# To loop through dates need to turn into sequence. | |
# SOLUTION | |
# do own date list | |
# watch out in for loop - use 1:length not just length | |
for (i in 1:length(date.list)){ | |
str(i) | |
str(date.list[i]) | |
print(paste0(date.list[i], ":", is.numeric(date.list[i]))) | |
} | |
dt <- data.table(x = c("p1","p2"), | |
max.date = date.list) | |
for (i in 1:length(unique(dt$max.date))) { | |
str(i) | |
str(dt[i, max.date]) | |
# print(paste0(dt[i, max.date], ":", is.numeric(dt[i, max.date]) )) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment