R语言学习笔记2-向量篇
2015-12-03 本文已影响121人
RudyHe
- vector
- x<-c(88,5,12,13)
- x<-c(x[1:3],168,x[4]) # 88 5 12 168 13
- length(x) # 5
- m<-rbind(c(1,2),c(3,4))
- m+10:13 # 11=1+10 14=3+11 14=2+12 17=4+13
- y<-vector(length=2) # declare 2-length vector
- y[1]<-5
- y[2]<-12
- y<-c(5,12)
- c(1,2,4)+c(6,0,9,20,22) # 7=1+6 2=2+0 13=4+9 21=1+20 24=2+22 with warning?
- x<-rbind(c(1,4),c(2,5),c(3,6))
- x+c(1,2) # [[2,6],[4,6],[4,8]] add c(1,2,1,2,1,2) 2=1+1 4=2+2 4=3+1 6=4+2 6=5+1 8=6+2
- "+"(2,3) # 2+3
- x<-c(1,2,4)
- x * c(5,0,-1) # 5 0 -4 dot product
- x / c(5,4,-1) # 0.2 0.5 -4.0
- x %% c(5,4,-1) # 1 2 0
- y<-c(1.2,3.9,0.4,0.12)
- y[c(1,3)] # 1.2 0.4
- y[2:3] # 3.9 0.4
- v<-3:4
- y[v] # 0.4 0.12
- x<-c(4,2,17,5)
- y<-x[c(1,1,3)] # 4 4 17
- x[-1] # 2 17 5 exclude 4
- x[-1:-2] # 17 5 exclude 4 and 2
- x[-length(x)] # 4 2 17 exclude 5
- x[1:(length(x)-1)] # same as above
- 5:8 # 5 6 7 8
- i<-2
- 1:i-1 # 0 1 which means 1:i first, then -1
- seq
- seq(from=12,to=30,by=3) # 12 15 18 21 24 27 30
- seq(from=1.1,to=2,length=10) # 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0
- x<-c(5,12,13)
- seq(x) # 1 2 3
- x<-NULL
- seq(x) # integer(0)
- rep
- x<-rep(8,4) # 8 8 8 8 make 8 with 4 times
- rep(1:3,2) # 1 2 3 1 2 3
- rep(c(5,12,13),each=2) # 5 5 12 12 13 13
- any
- x<-1:10
- any(x>8) # TRUE
- any(x>88) # FALSE
- all(x>88) # FALSE
- all(x>0) # TRUE
- vector operation
runs<-NULL
for (i in 1:10) {
runs<-c(runs,i) # not good for performance
runs<-vector(length=n)
for (i in 1:n) {
runs[i]<-i # good
return(runs)
- y<-c(5,2,-3,8)
- cumsum(y) # 57 4 12
- u<-c(5,2,8)
- v<-c(1,3,9)
- u>v # TRUE FALSE FALSE
- w<-function(x) return(x+1)
- w(u) # 6 3 9
- sqrt(1:9) # 1.000000 1.414214 ... 3.000000
- y<-c(1.2,3.9,0.4)
- round(y) # 1 4 0
- '+'(u,4) # 9 6 12
- x<-1:8
- z12<-function(z) return (c(z,z^2))
- z12(x) # 1 2 3 4 5 6 7 8 1 4 9 16 25 36 49 64
- NA
- x<-c(88,NA,12,168,13)
- mean(x) # NA
- mean(x, na.rm=T) # 70.25
- x<-c(88,NULL,12,168,13)
- mean(x) # 70.25
- mode(x[2]) # "numeric"
- y<-c("abc","def",NA)
- mode(y[3]) # "character"
- z<-NA
- for (i in 1:10) if (i%%2==0) z<-c(z,i) # NA 2 4 6 8 10
- z<-NULL
- for (i in 1:10) if (i%%2==0) z<-c(z,i) # 2 4 6 8 10
- filter
- z<-c(5,2,-3,8)
- w<-z[z*z>8] # 5 -3 8
- ">"(2,1) # TRUE
- z*z>8 same as ">"(z*z,8)
- j<-z*z>8
- y<-c(1,2,30,5)
- y[j] # 1 30 5 TRUE FALSE TRUE TRUE
- x<-c(1,3,8,2,20)
- x[x>3]<-0 # 1 3 0 2 0
- which(z*z>8) # 1 3 4 index not value
- x<-c(6,1:3,NA,12)
- x[x>5] # 6 NA 12
- subset(x,x>5) # 6 12
- ifelse
- x<-1:10
- y<-ifelse(x%%2==0,5,12) # 12 5 12 5 12 5 12 5 12 5
- x<-c(5,2,9,12)
- ifelse(x>6,2*x,3*x) # 15 6 18 24
- args(ifelse) # function(test,yes,no) check function definition
- Test
- x<-1:3
- y<-c(1,3,4)
- x==y # TRUE FALSE FALSE
- all(x==y) # FALSE
- x<-1:2
- y<-c(1,2)
- identical(x,y) # FALSE
- typeof(x) # "integer"
- typeof(y) # "double"
- names(x) # NULL
- x<-c(1,2,4)
- names(x)<-c("a","b","ab")
- x["ab"] # 4 using as index
- names(x)<-NULL # remove names
- c(5,2,c(1.5,6)) # 5.0 2.0 1.5 6.0 make flat