R语言 生成具有指定水平的因子 – gl()函数

R语言 生成具有指定水平的因子 – gl()函数

R语言中的 gl() 函数用于通过指定其水平的模式来生成因子。

语法:

gl(x, k, length, labels, ordered)

参数:

x: 水平的数量

k: 复制的数量

length: 结果的长度

labels: 向量的标签(可选)

ordered: 布尔值,用于排列水平。

例1 :

# R Program to generate factors
  
# Creating a factor
# using gl() function
x1 <- gl(2, 5)
  
# gl() function with
# length specified
x2 <- gl(3, 4, 12)
  
# Printing the factors
print(x1)
print(x2)
R

输出

 [1] 1 1 1 1 1 2 2 2 2 2
Levels: 1 2
 [1] 1 1 1 1 2 2 2 2 3 3 3 3
Levels: 1 2 3
R

例2 :

# R Program to generate factors
  
# gl() function with
# length and labels specified
x1 <- gl(3, 4, 12, label = letters[1:12])
  
# gl() function with
# length, label and order specified
x2 <- gl(3, 4, 12, label = letters[1:12], ordered = T)
  
# Printing the factors
print(x1)
print(x2)
R

输出

 [1] a a a a b b b b c c c c
Levels: a b c d e f g h i j k l
 [1] a a a a b b b b c c c c
Levels: a < b < c < d < e < f < g < h < i < j < k < l
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册