Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert factor levels to list, in R

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.

like image 939
jpinelo Avatar asked May 09 '15 13:05

jpinelo


People also ask

How do I convert a factor to a data in R?

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().

How do I extract a level from a factor in R?

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).

How do I convert a factor variable to a character in R?

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).

What does levels () do in R?

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.


2 Answers

This converts the factor to something manageable:

df1$v1 <- vapply(df1$v1, paste, collapse = ", ", character(1L))
like image 150
Shashank Raina Avatar answered Oct 13 '22 03:10

Shashank Raina


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
like image 18
Phil Avatar answered Oct 13 '22 03:10

Phil