When you want to change the levels of the factor, just use:
levels(a) <- c("a"=2,"b"=3,"c"=4)
which gives:
> a
[1] 2 3 4
Levels: 2 3 4
As @joran showed in his answer, using names
works as well. However there is no specific need to use as.character
in my opinion:
names(a) <- 2:4
which gives:
> a
2 3 4
a b c
Levels: a b c
Additionally, you can use as.integer
as @joran showed.
With the names
argument you assign names to values. The levels
argument is only used for factor variables.
For example, when you set your vector like:
a <- 2:4
names(a) <- letters[1:3]
using levels(a)
, gives: NULL
When you set your vector like:
a <- 2:4
levels(a) <- c("ab","bc","cd")
using names(a)
, gives: NULL