swirl 7: Matrices and Data Frames

来源:互联网 发布:燕十八的php讲的怎么样 编辑:程序博客网 时间:2024/05/21 20:56

dim() The dim() function tells us the 'dimensions' of an object.

> dim(my_vector)
NULL

vector的dimension是NULL.

> length(my_vector)
[1] 20

> length(matrix(1:20,4,5))
[1] 20

length()返回vector matrix的“长度”,慎重使用。

cbind() Use the cbind() function to 'combine columns'. 

> patients <- c("Bill","Gina","Kelly","Sean")

> my_matrix <- matrix(1:20,4,5)

> 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"

If you remember back to the beginning of this lesson, I told you that matrices can only contain ONE class of data. Therefore, when we tried to combine a character vector with a numeric matrix, R was forced to 'coerce' the numbers to characters, hence the double quotes. This is called 'implicit coercion'.

> data.frame(patients, my_matrix)
  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

data.frame() the data.frame() function takes any number of arguments and returns a single object of class. `data.frame` that is composed of the original objects.

> class(my_data)
[1] "data.frame"

colnames() Now, use the colnames() function to set the `colnames` attribute for our data frame. 
> colnames(my_data) <- cnames

0 0
原创粉丝点击