15

Imagine a data frame such as df1 below:

df1 <- data.frame(v1 = as.factor(c("m0p1", "m5p30", "m11p20", "m59p60", "m59p60")))

How do I create a list of all the levels of a variable? Thank you.

2

2 Answers 2

18

To print the levels in the variable, use levels() as @scoa says:

levels(df1$v1)

To make it an explicit list use as.list() as well:

l <- as.list(levels(df1$v1))
l
4

This converts the factor to something manageable:

df1$v1 <- vapply(df1$v1, paste, collapse = ", ", character(1L))
1
  • you can do the same more simply with `as.caracter(df1$v1)' Aug 4, 2020 at 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.