Home > Software engineering >  Reordering vectors by frequency and order of entry
Reordering vectors by frequency and order of entry

Time:11-21

How can I reorder the following vectors in R by frequency and order of entry? For example:

Z1 <- c(1,1,1,2,2) # c(1,1,1,2,2)
Z2 <- c(2,2,2,1,1) # c(1,1,1,2,2)
Z3 <- c(2,3,5,5,4) # c(2,3,1,1,4)
Z4 <- c(2,4,5,5,3) # c(2,3,1,1,4)

I tried using the rank() function to order by order of entry as follows, but I can't figure out how to order them again by frequency. Any ideas?

as.numeric(factor(rank(Z1))) # c(1,1,1,2,2)
as.numeric(factor(rank(Z2))) # c(2,2,2,1,1)
as.numeric(factor(rank(Z3))) # c(1,2,4,4,3)
as.numeric(factor(rank(Z4))) # c(1,3,4,4,2)

CodePudding user response:

We may use the fct_infreq with fct_inorder from forcats

> library(forcats)
> as.integer(fct_infreq(fct_inorder(as.character(Z4))))
[1] 2 3 1 1 4
> as.integer(fct_infreq(fct_inorder(as.character(Z3))))
[1] 2 3 1 1 4
> as.integer(fct_infreq(fct_inorder(as.character(Z2))))
[1] 1 1 1 2 2
> as.integer(fct_infreq(fct_inorder(as.character(Z1))))
[1] 1 1 1 2 2
  • Related