本节主要讲述

  • Matrix: 只包含一种数据类型的数据
  • data.frame: 可以包含多种数据类型的数据

Matrix

通过vector引入matrix

> my_vector <- 1:20
> dim(my_vector)
NULL
> length(my_vector)
[1] 20

由于my_vector是向量,所以没有dim属性,想要知道vector的长度,可以使用length().

> dim(my_vector) <- c(4, 5) # 给my_vector对象设置了dim属性,此时my_vectori变成了矩阵
> dim(my_vector)
[1] 4 5
> my_vector
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   20

查看一个object有哪些属性?

> attributes(my_vector)
$dim
[1] 4 5

查看数据类型

> class(my_vector)
[1] "matrix"

介绍matrix

使用matrix函数创建没matrix

> my_matrix <- my_vector
> my_matrix2 <- matrix(data = 1:20, nrow = 4, ncol = 5)
> identical(my_matrix, my_matrix2)
[1] TRUE

给matrix增加一列

> patients <- c("Bill", "Gina", "Kelly", "Sean")
> cbind(patients, my_matrix)
     patients                       
[1,] "Bill"   "1" "5" "9"  "13" "17"
[2,] "Gina"   "2" "6" "10" "14" "18"
[3,] "Kelly"  "3" "7" "11" "15" "19"
[4,] "Sean"   "4" "8" "12" "16" "20"

此时我们发现矩阵所有元素都变成字符串类型,这样不是我们想要的,但是矩阵只能包含一种数据类型,所以没法搞。 此时引入data.frame来解决这个问题。

data.frame

> my_data <- data.frame(patients, my_matrix)
> my_data
  patients X1 X2 X3 X4 X5
1     Bill  1  5  9 13 17
2     Gina  2  6 10 14 18
3    Kelly  3  7 11 15 19
4     Sean  4  8 12 16 20

my_data的每一列起个名字

> cnames <- c("patient", "age", "weight", "bp", "rating", "test")
> colnames(my_data) <-  cnames # colnames和之前的dim有点像,修改对象的colnames属性
> my_data
  patient age weight bp rating test
1    Bill   1      5  9     13   17
2    Gina   2      6 10     14   18
3   Kelly   3      7 11     15   19
4    Sean   4      8 12     16   20

results matching ""

    No results matching ""