thiagoveloso
thiagoveloso

Reputation: 2763

R - combine data frames of different lengths after loop

I am looping through a series of 15 files. My loop looks like this:

for (i in 1:length(mod.f)) {
    do some stuff
    dataframe `df` is produced
}

Each iteration of the loop will yield a data frame with two columns - date and some value, just like the example below:

df <- structure(list(date = structure(c(-43829, -43798, -43770, -43739, 
-43709, -43678, -43648, -43617, -43586, -43556, -43525, -43495, 
-43464, -43433, -43405, -43374, -43344, -43313, -43283, -43252
), class = "Date"), inmcm4 = c(71.4782417258324, 68.5037706662898, 
64.0571482842429, 62.8708849771957, 66.3121740437669, 62.7535770507166, 
62.2819567665719, 62.3014754255822, 58.6247123853888, 58.4425949480101, 
61.3534245382973, 68.2531958750396, 70.4892992599108, 70.1840748468477, 
64.6298343911645, 66.5280510648649, 65.2767506692563, 62.8944646174169, 
60.4309882672837, 58.7368776782633)), .Names = c("date", "inmcm4"
), row.names = c(NA, 20L), class = "data.frame")

The problem here is that not all the data frames have the same length. The lengths of each data frame are the following:

1872 
1740 
1872 
1932 
1872 
1752 
1752 
1872 
1872 
672 
1872 
1872 
1956 
1956 
1872

As a result, not all dates (e.g. df$date) will be the same.

What I wish to do is to combine all data frames in one single data frame by the end of the loop. This final data frame should have a date column and the remaining columns would be the values of each iteration, assigning NA's to the dates that don't overlap.

Any ideas on how to do this?

Thanks!

Upvotes: 1

Views: 957

Answers (1)

akrun
akrun

Reputation: 887691

You can try

 Reduce(function(...) merge(..., by='date', all=TRUE), lst)

where lst is the list of data.frames

data

set.seed(24)
df2 <- df[sample(1:nrow(df),8, replace=FALSE),]
row.names(df2) <- NULL
lst <- list(df, df2)

Upvotes: 1

Related Questions