简体   繁体   中英

Iterating through unknown dates in R

I'm new to R (having worked in C++ and Python before) so this is probably just a factor of me not knowing some of R's nuances.

The program I'm working on is supposed to construct matrices of data by date. Here's how I might initialize such a matrix:

dates <- seq(as.Date("1980-01-01"), as.Date("2013-12-31"), by="days")
HN3 <- matrix(nrow=length(dates), ncol = 5, dimnames = list(as.character(dates), c("Value1", "Value2", "Value3", "Value4", "Value5")))

Notice that dates includes every day between 1980 and 2013.

So, from there, I have files containing certain dates and measurements of Value1 , etc for those dates, and I need to read those files' contents into HN3 . But the problem is that most of the files don't contain measurements for every day .

So what I want to do is read a file into a dataframe (say, v1read ) with column 1 being dates and column 2 being the desired data. Then I'd match the dates of v1read to that date's row in HN3 and copy all of the relevant v1read values that way. Here is my attempt at doing so:

for (i in 1:nrow(v1read)) {
  HN3[as.character(v1read[i,1]),Value1] <- v1read[i,4]
}

This gives me an out of index range error when the value of i is bumped up unexpectedly. I understand that R doesn't like to iterate through dates, but since the iterator itself is a numeric value rather than a date, I was hoping I'd found a loophole.

Any tips on how to accomplish this would be enormously appreciated.

Let's use library(dplyr) . Start with

dates = seq(as.Date("1980-01-01"), as.Date("2013-12-31"), by="days")
HN3 = data.frame(Date=dates)

Now, load in your first file, the one that has a date and Value1.

file1 = read.file(value1.file) #I'm assuming this file has a column already named "Date" and one named #Value1
HN3 = left_join(HN3,file1,by="Date")

This will do a left join (SQL style) matching only the rows where a date exists and filling in the rest with NA. Now you have a data frame with two columns, Date and Value1. Load in your other files, do a left_join with each and you'll be done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM