I have data with very messy factor level names, which are sometimes more than a sentence long. For that reason I would prefer to refer to the levels by number to rename them (instead of the usual factor level name). For the example data below, how could I rename the factor level (let's say to "G", "S1" and "S2"), without mentioning "gravel", "sandstone" or "siltstone"?
df <- data.frame(x = c("gravel", "sandstone", "siltstone"))
CodePudding user response:
You can change it with levels<-
.
df <- data.frame(x = c("gravel", "sandstone", "siltstone"), stringsAsFactors = TRUE)
levels(df$x)
#[1] "gravel" "sandstone" "siltstone"
levels(df$x) <- c('G', 'S1', 'S2')
levels(df$x)
#[1] "G" "S1" "S2"
df
# x
#1 G
#2 S1
#3 S2
CodePudding user response:
We may call factor
with labels
df$x <- factor(df$x, labels = c("G", "S1", "S2"))
df$x
[1] G S1 S2
Levels: G S1 S2
data
df <- data.frame(x = c("gravel", "sandstone", "siltstone"), stringsAsFactors = TRUE)