0

I notice that in R, if you use levels to change the order of the levels in a factor column, you actually change the content of the data. For example:

test <- data.frame(name=c("A","B","C"), age=c(20,21,22))
test$name <- as.factor(test$name)
levels(test$name) <- c("C","B","A")

Then in test, it becomes that C has age 20, A has age 22, instead of the original content where A has age 20 and C has age 22.

How can I change the levels of a factor without changing the actual content?

Steve
  • 4,935
  • 11
  • 56
  • 83

1 Answers1

1

We can specify the levels in factor call

test$name <- factor(test$name, levels= c("C", "B", "A"))

It will only change the order of the levels and not the data

test$name
#[1] A B C
#Levels: C B A
akrun
  • 874,273
  • 37
  • 540
  • 662