Vector
> c(2,3,5.5,7.1,2.1,3)[1] 2.0 3.0 5.5 7.1 2.1 3.0> assign("v",c(2,3,5.5,7.1,2.1,3))> v <- 1:10> v [1] 1 2 3 4 5 6 7 8 9 10> rep(2,10) [1] 2 2 2 2 2 2 2 2 2 2> seq(1,5,by=0.5)[1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0> seq(length=10,from=1,by=0.5) [1] 1.0 1.5 2.0 2.5 3.0 3.5 4.0 4.5 5.0 5.5> v[3][1] 3> v + 1/v + 5 [1] 7.000000 7.500000 8.333333 9.250000 10.200000 11.166667 12.142857 13.125000 14.111111 15.100000> is.vector(v)[1] TRUE Array
> array(1:9)[1] 1 2 3 4 5 6 7 8 9> array(1:9,dim=c(3,3)) [,1] [,2] [,3][1,] 1 4 7[2,] 2 5 8[3,] 3 6 9> x <- 1:64> dim(x) <- c(2,4,8) #dim() converts the vector into array> is.array(x)[1] TRUE> x[1,,] [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8][1,] 1 9 17 25 33 41 49 57[2,] 3 11 19 27 35 43 51 59[3,] 5 13 21 29 37 45 53 61[4,] 7 15 23 31 39 47 55 63> dim(x)[1] 2 4 8> dim(x)[1][1] 2> dim(x)[2][1] 4> dim(x)[3][1] 8
Data Frame
> x <- BOD> is.matrix(x)[1] FALSE> is.data.frame(x)[1] TRUE> x Time demand1 1 8.32 2 10.33 3 19.04 4 16.05 5 15.66 7 19.8> y <- x[2,]> is.list(y)[1] TRUE> is.data.frame(y)[1] TRUE> x$Time[1] 1 2 3 4 5 7> x$demand[1] 8.3 10.3 19.0 16.0 15.6 19.8
判斷一個frame裡面是否包含某個值
> frame <- data.frame(x=c(1,2,3),y=c(4,5,6))> 3 %in% frame$x[1] TRUE> 3 %in% frame$y[1] FALSE> c(1,3) %in% frame$x[1] TRUE TRUE
Factor
> v <- c(1,3,5,8,2,1,3,5,3,5)> factor(v) [1] 1 3 5 8 2 1 3 5 3 5Levels: 1 2 3 5 8> factor(v, levels=c(2,1)) [1] 1 <NA> <NA> <NA> 2 1 <NA> <NA> <NA> <NA>Levels: 2 1> levels(x) <- c("two","one") Matrix
> matrix(c(3,5,7,1,9,4),nrow=3,ncol=2,byrow=TRUE) [,1] [,2][1,] 3 5[2,] 7 1[3,] 9 4#用which返回數組下標>a=c(1,3,4,5,3,2,5,6,3,2,5,6,7,5,8)#取數組a中最大值的下標>which.max(a)[1] 15#取數組a中最小值的下標>which.min(a)[1] 1#取數組a中大於3值的下標>which(a>3)[1] 3 4 7 8 11 12 13 14 15#取數組a中等於3值的下標>which(a==3)[1] 2 5 9
Matrix與Vector之間的關係
> v1 <- rnorm(5)> v2 <- rnorm(5)> v3 <- rnorm(5)> v1[1] -0.09606998 0.20435991 -2.05094095 -0.86723059 -0.03072555> mat <- matrix(c(v1,v2),nrow=length(v1))> mat <- cbind(mat,v3) #append by column would be cbind (column bind)> mat v3[1,] -0.09606998 1.8699476 -0.06645094[2,] 0.20435991 -0.2373573 0.27731764[3,] -2.05094095 -0.7309495 0.05417499[4,] -0.86723059 -1.6340647 0.81153156[5,] -0.03072555 0.2326525 0.93222996