Sort strings by R

I would like to do a series of sorting strings in csv using R. Here I have the following data

Name  English Math  French
John    56    78    86
Sam     79    97    86
Viru    93    44    34

I want to sort rows by the dataset above. As shown below.

Name  
John   French  86   Math 78  English 56 
Sam    Math    97   French 86 English 79  
Viru    English 93   Math 44   French 34

Please let me know how to approach

+4
source share
2 answers

If we need only sortrow by row, use applyc MARGIN=1and assign the output back to the original columns after transferring the output.

df1[-1] <- t(apply(df1[-1], 1, 
        FUN=function(x) sort(x, decreasing=TRUE)))

df1
#   Name English Math French
# 1 John      86   78     56
# 2  Sam      97   86     79
# 3 Viru      93   44     34

NOTE. But we may need to change the column names, as sorting by row gives new sorted values.


apply , , Map , cbind, .

nMat <- `dim<-`(names(df1)[-1][t(apply(df1[-1], 1,  
        order, decreasing=TRUE))], dim(df1[-1]))
vMat <- t(apply(df1[-1], 1,  sort, decreasing=TRUE))
cbind(df1[1], data.frame(Map(cbind, as.data.frame(nMat,
   stringsAsFactors=FALSE), as.data.frame(vMat))))
#  Name    V1.1 V1.2   V2.1 V2.2    V3.1 V3.2
#1 John  French   86   Math   78 English   56
#2  Sam    Math   97 French   86 English   79
#3 Viru English   93   Math   44  French   34

data.table. melt "" "long", "Name", we order "" "i", Data.table(.SD), ('N'), dcast 'long' 'wide'.

library(data.table)
dcast(melt(setDT(df1), id.var='Name')[order(-value), 
  .SD, Name][, N:=paste0("Col", 1:.N) , .(Name)],
    Name~N, value.var=c("variable", "value"))
#   Name variable_Col1 variable_Col2 variable_Col3 value_Col1 value_Col2 value_Col3
#1: John        French          Math       English         86         78         56
#2:  Sam          Math        French       English         97         86         79
#3: Viru       English          Math        French         93         44         34
+4

:

cbind(x[1],matrix(paste(colnames(x)[apply(x[,2:4],1,order,decreasing=TRUE)+1],
      apply(x[,2:4],1,sort,decreasing=TRUE)),ncol=3,byrow=TRUE))
#  Name          1         2          3
#1 John  French 86   Math 78 English 56
#2  Sam    Math 97 French 86 English 79
#3 Viru English 93   Math 44  French 34
+3

All Articles