如何更改R中因子的级别顺序?
在 R 编程语言中,因子用于通过唯一标识给定向量中的元素来表示分类数据。当应用因子函数时,它将返回唯一元素的级别。在本文中,我们将讨论如何更改因子的水平。
我们可以使用 factor()函数本身获得向量的水平
Syntax: factor(vector)
Parameters:
- vector: vector with categorical data
- levels(): specifies the levels
Returns: vector elements with levels
如果我们想改变级别的顺序,我们可以在 factor()函数指定levels参数
语法:
factor(vector,levels=c(elements))
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)
print(data)
#change the order of the levels
# from the resultant data
ordered_data=factor(data,levels=c(
'pinkey','rohith','sravan','bobby'))
print(ordered_data)
R
# Create a vector with elements
data =c(1,2,3,4,5.7,8.9,8.0,1,2,3)
# apply factor to vector to get
# unique data
data=factor(data)
print(data)
# change the order of the levels
# from the resultant data
ordered_data=factor(data,levels=c(
5.7,2,3,4,1,8,8.9))
print(ordered_data)
输出:
示例 2:
电阻
# Create a vector with elements
data =c(1,2,3,4,5.7,8.9,8.0,1,2,3)
# apply factor to vector to get
# unique data
data=factor(data)
print(data)
# change the order of the levels
# from the resultant data
ordered_data=factor(data,levels=c(
5.7,2,3,4,1,8,8.9))
print(ordered_data)
输出: