user288609
user288609

Reputation: 13015

Regarding sorting each row independently for a table

Currently, I have a csv file like the following one

ID      grade-1         grade-2         grade-3
 1    0.004461027   0.002740424 0.002955164
 2    0.055690775   0.045791653 0.17440305
 3    0.048901623   0.042439538 0.027306325
 4    0.20013265    0.0637944   0.081362503

I read table as

test.matrix<-data.frame(read.table("test.csv",sep=",",header=T))

I would like to generate a new table where each row was sorted

ID      highest grade           the second grade           the third grade
1   grade-1:0.004461027 grade-3:0.002955164        grade-2:0.002740424  
2   grade-3:0.17440305      grade-1:0.055690775    grade-2:0.045791653  
3   grade-1:0.048901623 grade-2:0.042439538    grade-3:0.027306325
4   grade-1:0.20013265  grade-3:0.081362503        grade-2:0.0637944    

How can I sort each row? And for generating the output, how to put a character, e.g., grade-1 and numerical value,e.g., 0.004461027 in a single entry, e.g., grade-1:0.004461027?

Upvotes: 1

Views: 121

Answers (2)

IRTFM
IRTFM

Reputation: 263301

Perhaps:

 res <- t( apply( dfrm[ 2:4], 1, 
                    function(row) paste0("grade-", 1:3, ":", rev(sort(row) ) ) ) )

R returns matrix results in column order, so when functions get applied to rows you need to transpose the result to get the ordinal "shape". To put the ID value back , cbind to ID:

 cbind(dfrm[, "ID", drop=FALSE], res)

I put the drop equal FALSE in there to keep the dataframe class of the first argument so the result would be a data.frame. Otherwise the res-object is a matrix and dfrm[ , "ID"] or dfrm$ID would be vectors and the cbind result would be a matrix.

Upvotes: 2

Roland
Roland

Reputation: 132651

t(apply(DF,1,function(x) {
  temp <- sort(x[-1],decreasing=TRUE)
  res <- c(x[1],paste(names(temp),temp,sep=": "))
  names(res) <- c("ID",      "highest grade",           "the second grade",           "the third grade")
  res
                        }))

     ID  highest grade          the second grade       the third grade       
[1,] "1" "grade.1: 0.004461027" "grade.3: 0.002955164" "grade.2: 0.002740424"
[2,] "2" "grade.3: 0.17440305"  "grade.1: 0.055690775" "grade.2: 0.045791653"
[3,] "3" "grade.1: 0.048901623" "grade.2: 0.042439538" "grade.3: 0.027306325"
[4,] "4" "grade.1: 0.20013265"  "grade.3: 0.081362503" "grade.2: 0.0637944"

Upvotes: 1

Related Questions