wpb
wpb

Reputation: 1

How do I make a categorical variable ordered from low to high?

Specifically, I am looking at some traits related to IUCN categories, which range from least concern to critically endangered, and I would like to order them as such e.g. (least endangered) LC, NT, VU, EN, CR (most endangered)

How would I order these so that R knows that there is an ascending ordr withing these categories?

Upvotes: 0

Views: 181

Answers (1)

Dan
Dan

Reputation: 12074

Here's an example of using an ordered factor as suggested by docendo discimus.

# Create dummy data frame
df <- data.frame(IUCN = sample(c("LC", "NT", "VU", "EN", "CR"), 20, replace = TRUE))

# Specify order of factors
df$IUCN <- factor(df$IUCN, levels = c("LC", "NT", "VU", "EN", "CR"), ordered = TRUE)

# Look at result
# > df$IUCN
# [1] NT LC CR EN NT LC LC EN NT NT EN LC NT LC NT NT LC CR EN VU
# Levels: LC < NT < VU < EN < CR

Upvotes: 1

Related Questions