match - R: Matching by row and column -
i have 2 data frames, below:
equitydata
valuationdate currency opening closing 02/01/2003 chf 0 0 02/01/2003 dkk 0 0 03/01/2003 chf 0 0 02/01/2003 sek 0 0 03/01/2003 sek 0 0 04/01/2003 sek 0 0 05/01/2003 chf 0 0 03/01/2003 dkk 0 0
which contains information trades done each day, in different currencies , historicalfx
date chf x dkk x.1 sek x.2 02/01/2003 0.6885 0.688 0.1347 0.1346 0.1094 0.1096 03/01/2003 0.688 0.6858 0.1346 0.1345 0.1096 0.1099 04/01/2003 0.6858 0.6858 0.1345 0.1345 0.1099 0.1099 05/01/2003 0.6858 0.6858 0.1345 0.1345 0.1099 0.1099
which contains historical fx rates, opening price below currency ticker, , closing price in column next it.
i trying corresponding fx price in equitydata data frame.
i have tried following, works, inefficient:
openexchangematch = match(equitydata$currency,colnames(historicalfx)) closeexchangematch = match(equitydata$currency,colnames(historicalfx))+1 datematch = match(equitydata$valuationdate,historicalfx$date) (i in 1:nrow(equitydata)) { equitydata$openexchange[i] = historicalfx[datematch[i],openexchangematch[i]] equitydata$closeexchange[i] = historicalfx[datematch[i],closeexchangematch[i]] }
any ideas on how can solve above in better way?
we create row/column index ('indx1') after subsetting second dataset ('df2' i.e. 'historicalfx'), assign 'opening' , 'closing' columns in first dataset ('df1' i.e. 'equitydata') values got using 'indx1' in 'op1' , 'cl1'
op1 <- df2[-1][c(true, false)] cl1 <- df2[-1][c(false, true)] names(cl1) <- names(op1) indx1 <- cbind(match(df1$valuationdate, df2$date), match(df1$currency, names(op1))) df1$opening <- op1[indx1] df1$closing <- cl1[indx1] df1 # valuationdate currency opening closing #1 02/01/2003 chf 0.6885 0.6880 #2 02/01/2003 dkk 0.1347 0.1346 #3 03/01/2003 chf 0.6880 0.6858 #4 02/01/2003 sek 0.1094 0.1096 #5 03/01/2003 sek 0.1096 0.1099 #6 04/01/2003 sek 0.1099 0.1099 #7 05/01/2003 chf 0.6858 0.6858 #8 03/01/2003 dkk 0.1346 0.1345
data
df1 <- structure(list(valuationdate = c("02/01/2003", "02/01/2003", "03/01/2003", "02/01/2003", "03/01/2003", "04/01/2003", "05/01/2003", "03/01/2003"), currency = c("chf", "dkk", "chf", "sek", "sek", "sek", "chf", "dkk"), opening = c(0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l), closing = c(0l, 0l, 0l, 0l, 0l, 0l, 0l, 0l)), .names = c("valuationdate", "currency", "opening", "closing"), class = "data.frame", row.names = c(na, -8l)) df2 <- structure(list(date = c("02/01/2003", "03/01/2003", "04/01/2003", "05/01/2003"), chf = c(0.6885, 0.688, 0.6858, 0.6858), x = c(0.688, 0.6858, 0.6858, 0.6858), dkk = c(0.1347, 0.1346, 0.1345, 0.1345 ), x.1 = c(0.1346, 0.1345, 0.1345, 0.1345), sek = c(0.1094, 0.1096, 0.1099, 0.1099), x.2 = c(0.1096, 0.1099, 0.1099, 0.1099)), .names = c("date", "chf", "x", "dkk", "x.1", "sek", "x.2"), class = "data.frame", row.names = c(na, -4l))
Comments
Post a Comment