Ranked returns in R -


returns <- data.frame(date = c('2015.01.01','2015.01.02','2015.01.03','2015.01.04'),                   asset1 = as.numeric(c('0.1','0.1','0.1','0.1')),                   asset2 = as.numeric(c('0.2','0.2','0.2','0.2')),                   asset3 = as.numeric(c('0.3','0.3','0.3','0.3')))  rank <- data.frame(date = c('2015.01.01','2015.01.02','2015.01.03','2015.01.04'),                   asset1 = as.numeric(c('3','3','3','3')),                   asset2 = as.numeric(c('1','1','1','1')),                   asset3 = as.numeric(c('2','2','2','2'))) 

i match rank 1 returns column 1 in new data frame. numbers , ranks can change quite bit moving column around won't work. think english didn't come out clear in first post. result should this.

result <- data.frame(date = c('2015.01.01','2015.01.02','2015.01.03','2015.01.04'),                          rank1 = as.numeric(c('0.2','0.2','0.2','0.2')),                          rank2 = as.numeric(c('0.3','0.3','0.3','0.3')),                          rank3 = as.numeric(c('0.1','0.1','0.1','0.1'))) 

as best ranked (for example sake) asset 2, column rank1 asset2 return. rank2 asset3 return ranked 2 whole time. these can change in real world, appreciate taking account.

here original answer, that, mix result. don't know doing actually.

result1 <- returns result1[-1] <- returns[-1][cbind(1:nrow(rank),as.numeric(t(rank[-1])))] 

we can use row/column indexing. order 'rank' numeric columns row ('ri'), use 'column' index, cbind row index (1:nrow(rank)), extract elements 'returns' dataset , assign 'result1' created earlier keep same structure.

 result1 <- returns  ri <- c(t(apply(rank[-1], 1, order)))  result1[-1] <- returns[-1][cbind(1:nrow(rank), ri)]  names(result1) <- sub('_.*', '', names(result1))  identical(result1, result)  #[1] true 

Comments

Popular posts from this blog

javascript - Chart.js (Radar Chart) different scaleLineColor for each scaleLine -

apache - Error with PHP mail(): Multiple or malformed newlines found in additional_header -

java - Android – MapFragment overlay button shadow, just like MyLocation button -