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.
There are two steps for converting factor to numeric: Step 1: Convert the data vector into a factor. The factor() command is used to create and modify factors in R. Step 2: The factor is converted into a numeric vector using as. numeric().
To extract the factor levels from factor column, we can simply use levels function. For example, if we have a data frame called df that contains a factor column defined with x then the levels of factor levels in x can be extracted by using the command levels(df$x).
To convert factor levels into character then we can use as. character function by accessing the column of the data frame that contain factor values. For example, if we have a data frame df which contains a factor column named as Gender then this column can be converted into character column as as. character(df$Gender).
levels provides access to the levels attribute of a variable. The first form returns the value of the levels of its argument and the second sets the attribute.
This converts the factor to something manageable:
df1$v1 <- vapply(df1$v1, paste, collapse = ", ", character(1L))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With