R类型7因子
Posted 克维拉
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了R类型7因子相关的知识,希望对你有一定的参考价值。
R语言因子
因子是用于对数据进行分类并将其存储为级别的数据对象,它们可以存储字符串和整数。 它们在具有有限数量的唯一值的列中很有用。 像“男性”,“女性
使用factor()函数通过将向量作为输入创建因子。
1创建
data <- c("East","West","East","North","North","East","West","West","West","East","North")
# Apply the factor function.
factor_data <- factor(data)//就这样创建
print(factor_data)
[1] East West East North North East West West West East North
Levels: East North West
print(is.factor(factor_data)) //TRUE
2更改级别顺序
可以通过使用新的等级次序再次应用因子函数来改变因子中的等级的顺序。
data <- c("East","West","East","North","North","East","West","West","West","East","North")
# Create the factors
factor_data <- factor(data)
print(factor_data)
# Apply the factor function with required order of the level.
new_order_data <- factor(factor_data,levels = c("East","West","North")) //这边更改了级别的顺序
print(new_order_data)
当我们执行上面的代码,它产生以下结果 -
[1] East West East North North East West West West East North
Levels: East North West
[1] East West East North North East West West West East North
Levels: East West North
3通过gl生成因子级别
我们可以使用gl()函数生成因子级别。 它需要两个整数作为输入,指示每个级别有多少级别和多少次。
gl(n, k, labels)
- n是给出级数的整数。
- k是给出复制数目的整数。
- labels是所得因子水平的标签向量。
v <- gl(3, 4, labels = c("Tampa", "Seattle","Boston")) //3个因子,复制数量4个
当我们执行上面的代码,它产生以下结果 -
Tampa Tampa Tampa Tampa Seattle Seattle Seattle Seattle Boston
[10] Boston Boston Boston
Levels: Tampa Seattle Boston
以上是关于R类型7因子的主要内容,如果未能解决你的问题,请参考以下文章
R将因子类型(Factor)转化为字符串类型(Character)