# How to convert factor levels to list in R ?

• Last Updated : 23 May, 2021

In this article, we are going to discuss how to convert the factor levels to list data structure in R Programming Language.

We can get the levels of the vector using factor() function

Syntax: factor(vector)

Return type: vector elements with levels.

If we want to get only levels, Then we can use levels() function.

Syntax: levels(factor(data))

Example 1: R program to create a character vector and get the levels and convert to list data structure

## R

 `# Create a vector with elements``data = ``c``(``"bobby"``, ``"sravan"``, ``"sravan"``,``         ``"pinkey"``, ``"rohith"``,``"rohith"``)`` ` `# apply factor to vector to get unique data``data = ``factor``(data)`` ` `# get the levels``levels = ``levels``(data)`` ` `# convert the levels to list``print``(``list``(levels))`

Output:

```[[1]]
[1] "bobby"  "pinkey" "rohith" "sravan"```

Example 2: R program to create a numeric vector and get the levels and convert to list data structure

## R

 `# Create a vector with elements``data = ``c``(1, 2, 3, 4, 5,``         ``6, 3, 4, 2, 4)`` ` `# apply factor to vector to get unique data``data = ``factor``(data)`` ` `# get the levels``levels = ``levels``(data)`` ` `# convert the levels to list``print``(``list``(levels))`

Output:

```[[1]]
[1] "1" "2" "3" "4" "5" "6"```

Example 3: convert levels to list of lists

Get each level into one list you can use as.list function.

Syntax: as.list(levels(data))

Code:

## R

 `# Create a vector with elements``data = ``c``(``"bobby"``, ``"sravan"``, ``"sravan"``,``        ``"pinkey"``, ``"rohith"``,``"rohith"``)`` ` `# apply factor to vector to get unique data``data = ``factor``(data)`` ` `# get the levels``levels = ``levels``(data)`` ` `# convert the levels to list of lists``print``(``as.list``(levels))`

Output:

```[[1]]
[1] "bobby"

[[2]]
[1] "pinkey"

[[3]]
[1] "rohith"

[[4]]
[1] "sravan"```

My Personal Notes arrow_drop_up