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
data = c ( "bobby" , "sravan" , "sravan" ,
"pinkey" , "rohith" , "rohith" )
data = factor (data)
levels = levels (data)
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
data = c (1, 2, 3, 4, 5,
6, 3, 4, 2, 4)
data = factor (data)
levels = levels (data)
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
data = c ( "bobby" , "sravan" , "sravan" ,
"pinkey" , "rohith" , "rohith" )
data = factor (data)
levels = levels (data)
print ( as.list (levels))
|
Output:
[[1]]
[1] "bobby"
[[2]]
[1] "pinkey"
[[3]]
[1] "rohith"
[[4]]
[1] "sravan"
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...