Home > OS >  R - Differences between a matrix with daily data and another with monthly data
R - Differences between a matrix with daily data and another with monthly data

Time:06-11

I have two matrices, one containing weekday data (delta_daily, dimension 5479 12) and the other one containing the monthly averages of the same data (delta_monthly, dimension 252 12). Now I need to calculate all the differences between daily values and the average value in the corresponding month. Basically, this is what I want to do:

set.seed(1) # R 4.1.2
delta_daily <- matrix(rnorm(64*12,0,2), ncol = 12)
set.seed(200)
delta_monthly <- matrix(rnorm(3*12,0,2), ncol = 12)

delta_daily[c(1,23,43):c(22,42,64),] - delta_monthly[1:3,])

However this obviously won't work due to more than one numerical expression within the brackets. How can I avoid this problem in order to multiply mutliple rows of delta_daily (not always the same number of rows) with a single row in delta_monthly?

CodePudding user response:

Assuming that you want to

  • subtract delta_monthly[1, ] from each row of delta_daily[1:22,]
  • subtract delta_monthly[2, ] from each row of delta_daily[23:42,]
  • subtract delta_monthly[3, ] from each row of delta_daily[43:64, ]

define a vector mon having an element for each row of delta_daily indicating which month (1, 2, 3) that row represents. Then expand delta_monthly to the same number of rows as delta_daily and subtract:

mon <- rep(1:3, c(22, 20, 22))
delta_daily - delta_monthly[mon, ]
  • Related