R语言数据类型

原子向量(基本类型)

  1. Logical(逻辑型)

TRUE, FALSE

  1. Numeric(数字)

12.3,5,999

  1. Integer(整型)

2L,34L,0L

  1. Complex(复合型)

3 + 2i

  1. Character(字符)

‘a’ , '“good”, “TRUE”, ‘23.4’

  1. Raw(原型)

v <- charToRaw(“Hello”)
“Hello” 被存储为 48 65 6c 6c 6f

Vectors 向量 、矢量

一组相同数据类型的数组

# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

Lists 列表

列表是一个R对象,它可以在其中包含许多不同类型的元素,如向量,函数甚至其中的另一个列表。

# Create a list.
list1 <- list(c(2,5,3),21.3,sin)

返回

[[1]]
[1] 2 5 3

[[2]]
[1] 21.3

[[3]]
function (x)  .Primitive("sin")

Matrices 矩阵

矩阵是二维矩形数据集。 它可以使用矩阵函数的向量输入创建。

# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)

返回

扫描二维码关注公众号,回复: 10183011 查看本文章
     [,1] [,2] [,3]
[1,] "a"  "a"  "b" 
[2,] "c"  "b"  "a"

Arrays 数组(阵列)

虽然矩阵被限制为二维,但阵列可以具有任何数量的维度。 数组函数使用一个dim属性创建所需的维数。 在下面的例子中,我们创建了一个包含两个元素的数组,每个元素为3x3个矩阵。

# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

返回

, , 1

     [,1]     [,2]     [,3]    
[1,] "green"  "yellow" "green" 
[2,] "yellow" "green"  "yellow"
[3,] "green"  "yellow" "green" 

, , 2

     [,1]     [,2]     [,3]    
[1,] "yellow" "green"  "yellow"
[2,] "green"  "yellow" "green" 
[3,] "yellow" "green"  "yellow"  

Matrices 矩阵

矩阵是二维矩形数据集。 它可以使用矩阵函数的向量输入创建。

# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)

返回

     [,1] [,2] [,3]
[1,] "a"  "a"  "b" 
[2,] "c"  "b"  "a"

Factors 因子

因子是使用向量创建的r对象。 它将向量与向量中元素的不同值一起存储为标签。 标签总是字符,不管它在输入向量中是数字还是字符或布尔等。 它们在统计建模中非常有用。
使用factor()函数创建因子。nlevels函数给出级别计数。

# Create a vector.
apple_colors <- c('green','green','yellow','red','red','red','green')

# Create a factor object.
factor_apple <- factor(apple_colors)

# Print the factor.
print(factor_apple)
print(nlevels(factor_apple))

返回

[1] green  green  yellow red    red    red    yellow green 
Levels: green red yellow
# applying the nlevels function we can know the number of distinct values
[1] 3

Matrices 矩阵

矩阵是二维矩形数据集。 它可以使用矩阵函数的向量输入创建。

# Create a matrix.
M = matrix( c('a','a','b','c','b','a'), nrow = 2, ncol = 3, byrow = TRUE)
print(M)

返回

     [,1] [,2] [,3]
[1,] "a"  "a"  "b" 
[2,] "c"  "b"  "a"

Data Frames 数据帧

数据帧是表格数据对象。 与数据帧中的矩阵不同,每列可以包含不同的数据模式。 第一列可以是数字,而第二列可以是字符,第三列可以是逻辑的。 它是等长度的向量的列表。
使用data.frame()函数创建数据帧。

# Create the data frame.
BMI <- 	data.frame(
   gender = c("Male", "Male","Female"), 
   height = c(152, 171.5, 165), 
   weight = c(81,93, 78),
   Age = c(42,38,26)
)
print(BMI)

返回

  gender height weight Age
1   Male  152.0     81  42
2   Male  171.5     93  38
3 Female  165.0     78  26  

参考:R语言 数据类型

发布了27 篇原创文章 · 获赞 3 · 访问量 1137

猜你喜欢

转载自blog.csdn.net/qq_39609993/article/details/103719003