R 编程中因子的级别排序
在本文中,我们将看到R 编程语言中因子的级别排序。
R – 因子的级别排序
因子是用于对数据进行分类并将其存储为级别的数据对象。它们可以存储字符串和整数。它们代表列,因为它们具有有限数量的唯一值。 R 中的因子可以使用factor()函数创建。它需要一个向量作为输入。 c()函数用于创建具有明确提供的值的向量。
例子:
R
x < - c("Pen", "Pencil", "Brush", "Pen",
"Brush", "Brush", "Pencil", "Pencil")
print(x)
print(is.factor(x))
# Apply the factor function.
factor_x = factor(x)
levels(factor_x)
R
# creating size vector
size = c("small", "large", "large", "small",
"medium", "large", "medium", "medium")
# converting to factor
size_factor <- factor(size)
print(size_factor)
# ordering the levels
ordered.size <- factor(size, levels = c(
"small", "medium", "large"), ordered = TRUE)
print(ordered.size)
R
# creating vector size
size = c("small", "large", "large", "small",
"medium", "large", "medium", "medium")
sizes <- ordered(c("small", "large", "large",
"small", "medium"))
# ordering the levels
sizes <- ordered(sizes, levels = c("small", "medium", "large"))
print(sizes)
输出 :
[1] “Pen” “Pencil” “Brush” “Pen” “Brush” “Brush” “Pencil” “Pencil”
[1] FALSE
[1] “Brush” “Pen” “Pencil”
在上面的代码中,x 是一个有 8 个元素的向量。要将其转换为因子,请使用函数factor() 。这里有8个因素和3个水平。级别是数据中的唯一元素。可以使用levels()函数找到。
订购因子水平
有序因子是因子的扩展。它按递增顺序排列级别。我们使用两个函数: factor()和参数ordered() 。
Syntax: factor(data, levels =c(“”), ordered =TRUE)
Parameter:
- data: input vector with explicitly defined values.
- levels(): Mention the list of levels in c function.
- ordered: It is set true for enabling ordering.
例子:
R
# creating size vector
size = c("small", "large", "large", "small",
"medium", "large", "medium", "medium")
# converting to factor
size_factor <- factor(size)
print(size_factor)
# ordering the levels
ordered.size <- factor(size, levels = c(
"small", "medium", "large"), ordered = TRUE)
print(ordered.size)
输出:
[1] small large large small medium large medium medium
Levels: large medium small
[1] small large large small medium large medium medium
Levels: small < medium < large
在上面的代码中,大小向量是使用 c函数创建的。然后将其转换为因子。并且对于排序 factor()函数与上述参数一起使用。因此尺寸按顺序排列。
使用有序函数也可以做到这一点。相同的示例如下所示:
例子:
R
# creating vector size
size = c("small", "large", "large", "small",
"medium", "large", "medium", "medium")
sizes <- ordered(c("small", "large", "large",
"small", "medium"))
# ordering the levels
sizes <- ordered(sizes, levels = c("small", "medium", "large"))
print(sizes)
输出:
[1] small large large small medium
Levels: small < medium < large