如何将因子水平转换为 R 中的列表?
在本文中,我们将讨论如何在 R 编程语言中将因子级别转换为列表数据结构。
我们可以使用 factor()函数获得向量的水平
Syntax: factor(vector)
Return type: vector elements with levels.
如果我们只想获取级别,那么我们可以使用levels()函数。
Syntax: levels(factor(data))
示例 1: R 程序创建字符向量并获取级别并转换为列表数据结构
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))
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))
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))
输出:
[[1]]
[1] "bobby" "pinkey" "rohith" "sravan"
示例 2: 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))
输出:
[[1]]
[1] "1" "2" "3" "4" "5" "6"
示例 3:将级别转换为列表列表
将每个级别放入一个列表中,您可以使用as.list函数。
Syntax: as.list(levels(data))
代码:
电阻
# 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))
输出:
[[1]]
[1] "bobby"
[[2]]
[1] "pinkey"
[[3]]
[1] "rohith"
[[4]]
[1] "sravan"