R语言 转换数据对象的类型 – type.convert() 函数
type. convert() 函数在R语言中用于计算特定数据对象的数据类型。
它可以将数据对象转换为逻辑、整数、数字或因子。
语法: type.convert(x)
参数:
x: 可以是一个向量矩阵或一个数组
例1:将type.convert应用于数字向量
# R program to illustrate
# type.convert to vector of numbers
# create an example vector
x1 <- c("1", "2", "3", "4", "5", "6", "7")
# Apply type.convert function
x1_convert <- type.convert(x1)
# Class of converted data
class(x1_convert)
输出:
[1] "integer"
在上面的代码中,我们可以看到在type.convert()函数之前,所有的数字都存储在其中,但它仍然是一个字符向量。而在这个函数之后,它变成了 “Integer”。
例2:一个既有字符又有整数的向量的类型转换。
# R Program to illustrate
# conversion of a vector with both characters and integers
# create an example vector
x1 <- c("1", "2", "3", "4", "5", "6", "7")
# Create example data
x2 <- c(x1, "AAA")
# Class of example data
class(x2)
# Apply type.convert function
x2_convert <- type.convert(x2)
# Class of converted data
class(x2_convert)
输出:
[1] "character"
[1] "factor"
这里,在上述代码中,在使用type.convert()函数后,有一些字符和一些整数。所以,输出的结果是一个因子。