[R] Sorting data frame by a string variable

S Ellison S.Ellison at lgc.co.uk
Wed Jul 18 11:19:04 CEST 2007


Dimitri

If you try 
> order(c("b","a","c"))
[1] 2 1 3

 or
> sort(c("b","a","c"))
[1] "a" "b" "c"
You will see that sort() and order() DO respect character order.

Your problem could be that your data frame variable is not a character but a factor (the default for read.table, for example)

Check the class of the variable. If it is a factor, try order(as.vector(String))

This will also work if String is a character vector; as.vector will just return the character variable. 


>>> "Dimitri Liakhovitski" <ld7631 at gmail.com> 17/07/2007 18:56:00 >>>
I have a data frame MyData with 2 variables.
One of the variables (String) contains a string of letters.
How can I resort MyData by MyData$String (alphabetically) and then
save the output as a sorted data file?

I tried:

o<-order(MyData$String)
SortedData<-rbind(MyData$String[o], MyData$Value[o])
write.table(SortedData,file="Sorted.txt",sep="\t",quote=F, row.names=F)


However, all strings get replaced with digits (1 for the first string,
2 for the second string etc.). How can I keep the strings instead of
digits?

Thank you!
Dimitri

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help 
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html 
and provide commented, minimal, self-contained, reproducible code.

*******************************************************************
This email and any attachments are confidential. Any use, co...{{dropped}}



More information about the R-help mailing list