Recoding an arbitrary group variable or factor into R
Suppose I have a vector or column of arbitrary length, representing some group / factor-variable with an arbitrary number of groups and arbitrary values for the same in rows:
a <- c(2,2,2,2,2,7,7,7,7,10,10,10,10,10)
a
[1] 2 2 2 2 2 7 7 7 7 10 10 10 10 10
How would I easily turn it into this:
a
[1] 1 1 1 1 1 2 2 2 2 3 3 3 3 3
+3
source to share
1 answer
a <- c(2,2,2,2,2,7,7,7,7,10,10,10,10,10)
c(factor(a))
#[1] 1 1 1 1 1 2 2 2 2 3 3 3 3 3
Explanation:
A factor is an integer vector with an attribute levels
and a class attribute. c
removes attributes as a side effect. You can use as.numeric
or as.integer
instead c
with similar or identical results respectively.
+4
source to share