aggregate - Counting in R and preserving the order of occurence -


suppose have generated vector using following statement:

x1 <- rep(4:1, sample(1:100,4)) 

now, when try count number of occurrences using following commands

count(x1)   x freq 1 1   40 2 2   57 3 3    3 4 4   46 

or

as.data.frame(table(x1))   x1 freq 1  1   40 2  2   57 3  3    3 4  4   46 

in both cases, order of occurrence not preserved. want preserve order of occurrence, i.e. output should this

  x1 freq 1  4   46 2  3    3 3  2   57 4  1   40 

what cleanest way this? also, there way coerce particular order?

one way convert variable factor , specify desired order levels argument. ?table: "table uses cross-classifying factors build contingency table of counts @ each combination of factor levels"; "it best supply factors rather rely on coercion.". converting factor yourself, in charge on coercion , order set levels.

x1 <- rep(factor(4:1, levels = 4:1), sample(1:100,4))  table(x1) # x1 #  4  3  2  1  #  90 72 11 16  

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -