質問

From a vector a I'm looking for a function (quick to compute) that returns a vector with numbers ranging between 1 and the number of levels in vector a and indicating which values are equal.

I know how to do this with a for loop but it is a bit slow to run.

a=vector(11,14,11,22,14,22)

levels(as.factor(a))==3

Solution

 b=vector(1,2,1,3,2,3)

meaning that in position 1 and 3 (where are the numbers 1 in b) the values in a are equal. in position 2 and 5 (where are the numbers 2 in b) the values in a are equal. etc...

Thank you

役に立ちましたか?

解決

You can use as.numeric() on a factor to get this:

a <- c(11,14,11,22,14,22)
as.numeric(factor(a))
# [1] 1 2 1 3 2 3

他のヒント

Here is one function thats quickily made:

numberfun <- function(x){y <- unique(x)
                         match(x,y)}

a <- c(11,14,11,22,14,22)
numberfun(a)
#[1] 1 2 1 3 2 3

a <- c(99,99,22,22,44,22,99)
numberfun(a)
#[1] 1 1 2 2 3 2 1
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top