r - Data Frame from Matrix having indices -
i have matrix has indices of columns of data frame. want construct data frame using value corresponding index, in same order in matrix.
the matrix created result of m1 <- sapply(df[,5:58],function(x){order(-x)})
df original dataframe 258 rows , 59 columns. matrix(258x54) result of sorting each of 54 columns of data frame independently want create dataframe have top 10 values each column.
how result dataframe matrix indices(m1) have values corresponding original dataframe (df) in order specified matrix position. loop solution build data frame, there apply or other function this?
i found solution using mapply:
matrix(mapply(function(x,y){df[x,y]}, as.list(t(m1)),rep((5:58),258)), nrow=258,ncol=54,byrow=t)
suppose, if data (though didn't understand logic):
set.seed(14) dat <- as.data.frame(matrix(sample(1:80, 258*59,replace=true), ncol=59)) m1 <- sapply(dat[,5:58], function(x) order(-x)) res1 <- matrix(dat[cbind(c(t(m1)),rep(5:58,258))],nrow=258, ncol=54, byrow=true)
your solution
res2 <- matrix(mapply(function(x,y){dat[x,y]}, as.list(t(m1)),rep((5:58),258)), nrow=258,ncol=54,byrow=t) identical(res1,res2) #[1] true
Comments
Post a Comment