How to use the order function to order a negative value?

I am trying to use a function orderto arrange a column of a table,

a<-c("-2","-7","-4")
b<-c("9","-1","3")


z<-data.frame(a,b)

When I want to order Z by column a, from largest to smallest, until it works. The function sets a negative value in its absolute value.

z[order(z$a,decreasing=TRUE),]
+3
source share
2 answers

If you need to convert the coefficients to numeric, you must, as described in the FAQ, first convert to tna, and then to numeric:

 str(z)
#'data.frame':  3 obs. of  2 variables:
# $ a: Factor w/ 3 levels "-2","-4","-7": 1 3 2
# $ b: Factor w/ 3 levels "-1","3","9": 3 1 2

z[order( as.numeric(as.character(z$a)), decreasing=TRUE ), ]
   a  b
1 -2  9
3 -4  3
2 -7 -1

(Explanation: Factors, unless of course they are β€œordered factors,” are not ordered, and comparisons with β€œ>” or β€œ<” return NA.

> z$a[1] > z$a[2]
[1] NA
Warning message:
In Ops.factor(z$a[1], z$a[2]) : > not meaningful for factors

, , - , , . )

> z$a
[1] -2 -7 -4
Levels: -2 -4 -7
> as.numeric(z$a)
[1] 1 3 2
+1

:

x <- c(2, 4, 0.5, -0.5 ,-1, 3,10) 
print(x) 
2.0  4.0  0.5 -0.5 -1.0  3.0 10.0
> order(x)
 5 4 3 1 6 2 7 # Not cool

> match(x, sort(x)) 
4 6 3 2 1 5 7 # Cool
0

All Articles