创建向量和矩阵
2019-07-27 本文已影响0人
唐伯虎点蚊香7
创建向量和矩阵
1、新建向量:c()
c(1,7:9)
[1] 1 7 8 9
> c(1:5, 10.5, "next")
[1] "1" "2" "3" "4" "5" "10.5" "next"
2、新建连续有规则向量:seq()
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL, ...)
> seq(0, 1, length.out = 11)
[1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
> seq(stats::rnorm(20))
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> seq(1, 9, by = 2)
[1] 1 3 5 7 9
> seq(1, 9, by = pi)
[1] 1.000000 4.141593 7.283185
> seq(17) # same as 1:17, or even better seq_len(17)
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
3、新建矩阵:matrix()
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL)
> mdat <- matrix(c(1,2,3, 11,12,13), nrow = 2, ncol = 3, byrow = TRUE,
+ dimnames = list(c("row1", "row2"),
+ c("C.1", "C.2", "C.3")))
> mdat
C.1 C.2 C.3
row1 1 2 3
row2 11 12 13