R_常用数据类型

常用的数据类型

数值型(Numeric):

包括所有实数,可以使用 as.numeric() 或 as.double() 函数将其他类型转换为数值型。

a <- 3
b <- 2.5
c <- as.numeric("1.5")
d <- as.double(TRUE)

 

整数型(Integer):

包括所有整数,可以使用 as.integer() 函数将其他类型转换为整数型。

a <- 5L
b <- as.integer("3")
c <- as.integer(FALSE)

 

字符型(Character):

包括所有字符,可以使用单引号或双引号括起来,也可以使用 as.character() 函数将其他类型转换为字符型。

a <- "Hello, world!"
b <- 'R programming'
c <- as.character(123)
d <- as.character(3.14)

 

 

逻辑型(Logical):

包括 TRUE 和 FALSE 两个值,可以使用 as.logical() 函数将其他类型转换为逻辑型。

a <- TRUE
b <- FALSE
c <- as.logical(1)
d <- as.logical("FALSE")

 

因子型(Factor):

用于表示分类数据,可以使用 factor() 函数将字符型或整数型转换为因子型。

a <- factor(c("red", "green", "blue"))
b <- factor(c(2, 1, 3), levels = c(1, 2, 3), labels = c("low", "medium", "high"))

 

列表型(List):

包括多个元素,每个元素可以是不同的数据类型,可以使用 list() 函数创建列表型对象。

a <- list("apple", 3.14, TRUE, c(1, 2, 3))
b <- list(name = "John", age = 25, gender = "male")

 

数组型(Array):

是一种多维的数值型数据结构,可以使用 array() 函数创建数组型对象。

a <- array(1:12, dim = c(3, 4))
b <- array(1:24, dim = c(2, 3, 4))

 

矩阵型(Matrix):

是一种特殊的数组型,只包含两个维度(行和列),可以使用 matrix() 函数创建矩阵型对象。

a <- matrix(1:9, nrow = 3, ncol = 3)
b <- matrix(letters[1:6], nrow = 2, ncol = 3, byrow = TRUE)

这些是常用的 R 数据类型及其实例。了解不同的数据类型可以帮助你更好地操作和处理数据。

THE END