Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recoding an arbitrary grouping variable or factor in R

Tags:

r

recode

Suppose I have a vector or column of arbitrary length representing some grouping/factor variable with an arbitrary number of groups and arbitrary values for same along the lines of this:

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 most easily turn that into this:

a
[1] 1  1  1  1  1  2  2  2  2  3  3  3  3  3
like image 820
Alexis Avatar asked Jul 14 '26 23:07

Alexis


1 Answers

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 just an integer vector with levels attribute and a class attribute. c removes attributes as a side effect. You could use as.numeric or as.integer instead of c with similar or the same results, respectively.

like image 197
Roland Avatar answered Jul 18 '26 08:07

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!