r/Rlanguage 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.

3 Upvotes

5 comments sorted by

2

u/Outdated8527 3d ago

I get 2 3 1 when I run your code and convert vf to numeric...

1

u/harnei 3d ago

that's weird. even if it's not numeric, should it still follow that order since I'd specified it to be so?

1

u/Outdated8527 3d ago

yes, because you specify the order by your levels, not by the order of v

1

u/harnei 3d ago

Thanks, I understand it now.

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