R语言中的数据类型
对于任何语言的编程,变量都起着重要的作用。变量用于保留内存空间,然后我们可以通过在该变量中存储一些值来利用它。
存储的值可以是任何类型的。例如,整数、浮点数、双数、字符串或布尔值。所有这些数据类型都用于在内存中保留不同的空间。
与其他编程语言不同,R语言的数据类型与它们不一样。在R语言中,变量被分配给R对象,R对象的数据类型成为变量的数据类型。
R语言中的数据类型有。
- 向量
- 列表
- 矩阵
- 数组
- 因子
- 数据框架
其中最容易和最简单的是向量。向量有6个分支,它们被称为原子向量,也被称为6类向量。
向量的类别
Data Types | Example |
---|---|
Logical | True, False |
Numeric | 11, 5.6, 0.99 |
Integer | 3L, 6L, 10L |
Complex | 6+i |
Character | ‘R’, “Language” |
Raw | “Hello” is stored as 48 65 6c 6c 6f |
请记住,在R语言中,类的数量并不局限于上述类型。利用原子向量,我们可以创建一个数组,其类可以进一步被认为是一个数组。
向量
c() 函数用于在向量中使用一个以上的元素时合并元素。
# Create a vector.
apple <- c('geeks', 'for', "benefit")
print(geeks)
# Get the class of the vector.
print(class(geeks))
输出
"geeks" "for" "benefit"
"character"
列表
列表是一种R对象,它可以将一个以上的元素甚至另一个列表结合在一起。
# Create a list.
list1 <- list(c(4, 5, 6), 22.7, cos)
# Print the list.
print(list1)
输出
[[1]]
[1] 4, 5, 6
[[2]]
[1] 22.7
[[3]]
function (x) .Primitive("cos")
矩阵
它是一个具有二维的数据集。它可以通过使用 矩阵() 函数的矢量输入来创建。
# Create a matrix.
S = matrix(c('a', 'b', 'c', 'd', 'e', 'f'),
numberOfRow = 2, numberOfCol = 3,
byRow = TRUE)
print(M)
输出
[, 1] [, 2] [, 3]
[1, ] "a" "b" "c"
[2, ] "d" "e" "f"
数组
与矩阵不同,数组可以是多维的。在数组中,”dim “变量取我们需要创建的维数。
# Create an array.
a <- array(c('grapes', 'mango'), dim = c(3, 3, 2))
print(a)
输出
,, 1
[, 1] [, 2] [, 3]
[1, ] "grapes" "mango" "grapes"
[2, ] "mango" "grapes" "mango"
[3, ] "grapes" "mango" "grapes",, 2
[, 1] [, 2] [, 3]
[1, ] "mango" "grapes" "mango"
[2, ] "grapes" "mango" "grapes"
[3, ] "mango" "grapes" "mango"
因子
向量被用来创建作为R-Objects的因子。与元素的不同值一起,因子存储向量作为标签。
标签总是一个字符。 factor() 函数用于创建因子。 nlevel() 函数总是计算级别的数量。
# Create a vector
colors <- c('green', 'green', 'yellow',
'red', 'red', 'red', 'green')
# Create a factor object.
factor <- factor(colors)
# Print the factor.
print(factor)
print(nlevels(factor))
输出
[1] green green yellow red red red green
Levels: green red yellow
[1] 3
数据框架
表格式的数据R-Objects被称为数据框架。基本上,它是矩阵的一种。但与矩阵不同,数据帧可以存储不同形式的模式。它是一个具有相同长度的向量。 data.frames() 函数被用来创建数据框架。
# Create the data frame.
employee <- data.frame(
gender = c("Male", "Male", "Female"),
height = c(152, 171.5, 165),
weight = c(81, 93, 78),
Age = c(42, 38, 26)
)
print(employee)
输出
gender height weight Age
1 Male 152.0 81 42
2 Male 171.5 93 38
3 Female 165.0 78 26