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?