[R] using string variable as order() function argument

mirek 3mirek at gmail.com
Mon Jul 26 20:56:57 CEST 2010


Hello,

In my script I would like to use a loop, which sorts the dataframe 
according to different columns, pointed by the string variable.

     id col1  col2  col3
1   10    0    4      8
2   11    1    2      2
3   12    0    8      3
4   13    0    5      5

Usually the order() function can be used like this:

sorted = mytable[order(column3) , ]

which results in properly sorted table:

     id col1  col2  col3
2   11    1    2      2
3   12    0    8      3
4   13    0    5      5
1   10    0    4      8

But when trying to use a string variable instead of "column3" name:

columnname = "column3"
sorted = mytable[order(columnname) , ]

this command is not properly evaluated and the effect is somewhat strange.

Would you suggest some solution?

Thanks a lot!

Mirek



More information about the R-help mailing list