-2

I currently have two tables, endingStock and totalUsage, with each row in each table having a date entry. I want to iterate over the rows of each table, compare the date, and if the dates are the same, I want to extract the value of a variable unit value from both endingStock and totalUsage, and append endingstock$unitvalue / totalUsage$unitvalue to a third table, ratioTable.

Using a bunch of different answers on this site, I've tried setting ratioTable to NULL and building up the table row by row, using the following loop:

for (i in 1:nrow(endingStocks)) {
  for (j in 1:nrow(useTotals)) {
    if (endingStocks[i,]$valuedate == useTotals[j,]$valuedate) {
      ratio = endingStocks[i,]$`unit value` / useTotals[j,]$`unit value`
      newrow <- c(endingStocks[i,]$valuedate, ratio)
      ratioTable <- rbind(ratioTable, newrow)
    }
  }
}

However, this seems to be skipping values. Each dataframe has over 200 entries that are roughly matched in terms of date, and so the resultant ratioTable should have the same order of entries, but instead only has 24.

1) Is there a way to effectively do this using vectorized operations?

2) Are there any glaring faults with my code?

  • Possible duplicate of [How to join (merge) data frames (inner, outer, left, right)?](http://stackoverflow.com/questions/1299871/how-to-join-merge-data-frames-inner-outer-left-right) – zx8754 Jun 07 '16 at 11:03

1 Answers1

0

I'm guessing without a reproducible example, but I think using merge will do what you want:

ratioTable = merge(endingStocks, totalUsage, by="valuedate")

You can then tidy your new table as required.

MikeRSpencer
  • 1,276
  • 10
  • 24