r - Most efficient way of ordering columns and creating rank variables -
i have data frame several columns. want create function/loop or might more efficient take data frame, order column, create variable rank(with name rank_columnname) based on order , add data frame.
dat <- data.frame(indi1=rnorm(10),indi2=rnorm(10)) dat1 <- dat[order(dat$indi1), ] dat1$rank_indi <- 1:nrow(dat) dat2 <- dat1[order(dat1$indi2), ] dat2$rank_indi2 <- 1:nrow(dat2)
this example want, in cumbersome way. i've tried using lapply can't seem update data frame new column similar name.
any appreciated.
here's simple loop insert in "rank_indi" variables:
for(i in names(dat)){ dat[order(dat[,i]),paste0("rank_", i)] <- 1:nrow(dat) } dat indi1 indi2 rank_indi1 rank_indi2 1 1.45829065 -0.3322692 10 2 2 0.55972129 2.5031318 7 10 3 0.45870293 -0.6216859 6 1 4 1.03814922 1.4284271 9 8 5 -0.75211259 0.5600499 3 4 6 -1.89298552 0.8047825 2 6 7 0.03843679 0.6593377 5 5 8 -0.09808913 0.2513729 4 3 9 0.97862797 2.2650003 8 9 10 -2.07767889 1.0684134 1 7
edit: made mistake in earlier code
Comments
Post a Comment