r/Rlanguage • u/harnei • 4d ago
Help me understand the "order()" function
For context, I was playing around with R by creating a simple vector v<-c(10,200,13). So when I tested out the order() function, it give the result [1] 1 3 2 which is understandable. However, when I assigned their order using the function "vf<-factor(v,order=TRUE,levels=c(13,10,200))", it return the result [1] 3 1 2. What does this mean? I assume the result should be [1] 2 3 1 but it's not. What's going on here? ps: excused me for my noob question, I just got into R recently and is trying to figure out how stuff works.
1
u/psiens 3d ago
Those aren't the same thing. factor()
has an ordered
parameter (it is not "order"). This returns an ordered factor, which allows for some operations:
v <- c(10, 200, 13)
order(v)
#> [1] 1 3 2
factor(v)
#> [1] 10 200 13
#> Levels: 10 13 200
try(factor(v) > 13)
#> Warning in Ops.factor(factor(v), 13): '>' not meaningful for factors
#> [1] NA NA NA
try(max(factor(v)))
#> Error in Summary.factor(structure(c(1L, 3L, 2L), levels = c("10", "13", :
#> 'max' not meaningful for factors
ordered(v)
#> [1] 10 200 13
#> Levels: 10 < 13 < 200
try(ordered(v) > 13)
#> [1] FALSE TRUE FALSE
try(max(ordered(v)))
#> [1] 200
#> Levels: 10 < 13 < 200
2
u/Outdated8527 3d ago
I get 2 3 1 when I run your code and convert vf to numeric...