如何在 R 中重新排序因子水平?
在本文中,我们将研究使用 R 编程语言中的函数对因子水平进行重新排序的方法。
使用 factor()函数对因子水平进行重新排序是对因子水平进行重新排序的最简单方法,因为这里用户需要调用因子函数并存储因子水平以及需要从以前的因子水平作为函数参数,这个过程将导致用户在函数参数中指定的因子水平的重新排序。
Factor()函数用于将向量编码为因子。
Syntax: factor(x = character(), levels)
Parameters:
- x: a vector of data, usually taking a small number of distinct values.
- levels: an optional vector of the unique valuesthat x might have taken.
示例 1:重新排序因子水平
初始级别:
[1] "A" "B" "C" "D" "E" "F" "G"
R
# Creating Data
gfg<-data.frame(x=factor(c('A','B','C','D','E','F','G')),
y=c(6,8,7,5,3,9,1))
# Reordering Levels
gfg$x <- factor(gfg$x, levels=c('G','F','E','C','D','B','A'))
gfg <- gfg[order(levels(gfg$x)),]
# Displaying Levels
levels(gfg$x)
R
# Creating Data
gfg<-data.frame(x=factor(c('G','F','E','C','D','B','A')),
y=c(6,8,7,5,3,9,1))
# Reordering Levels
gfg$x <- factor(gfg$x, levels=c('A','B','C','D','E','F','G'))
gfg <- gfg[order(levels(gfg$x)),]
# Displaying Levels
levels(gfg$x)
输出:
[1] "G" "F" "E" "C" "D" "B" "A"
示例 2:重新排序因子水平
初始级别:
'G','F','E','C','D','B','A'
R
# Creating Data
gfg<-data.frame(x=factor(c('G','F','E','C','D','B','A')),
y=c(6,8,7,5,3,9,1))
# Reordering Levels
gfg$x <- factor(gfg$x, levels=c('A','B','C','D','E','F','G'))
gfg <- gfg[order(levels(gfg$x)),]
# Displaying Levels
levels(gfg$x)
输出:
[1] "A" "B" "C" "D" "E" "F" "G"