Saturday, October 27, 2007

Vector

# initialization
> vector('logical',3) = logical(3)
> vector('numeric',4) = numeric(4)
> vector('complex',5) = complex(5)
> vector('character',5) = character(5)

# vector
length( ), mode( ), names( )

### examples for vector
> X <- 2*(1:20)
> X[X<=10] [1] 2 4 6 8 10
> X[-(1:17)] [1] 36 38 40
> X[-c(4,7)]
> Y[c(1,5,20)] <- 1 // assess the value 1 at element 1,5,20
> y[y<0] <- -y[y<0] == y <- abs(y)
> y <- c(6,7,8)
> z <- c(y,x,y)
> u <- scan() // input by keyboard

> rep(c(4,2),times=2)
> rep(c(4,2),times=c(3,2)) [1] 4 4 4 2 2
> rep(c(1,5),length=5) [1] 1 5 1 5 1

> seq(1,11,by=3) [1] 1 4 7 10
> seq(1,11,length=4) [1] 1.000000 4.333333 7.666667 11.000000
> rev(seq(1,9,by=2)) [1] 9 7 5 3 1 // reverse
> unique(x) // return the value which is unique
> sort(x) // sorts data in ascending order
> rev(sort(x)) // descending order
> rank(x) // returns the ranks of the input, average
> order(x) // sort(x) - x[order(x)]
> rle(x) // length and value of runs of the same value

> height <- c(170,180,163); names(person) <- c('a','b','c')
> height <- append(height, 200, after=2)
> height <- replace(height, 2, 192) = height[2]<-192
> height <- replace(height, c(1,3), c(166,159))

> x <- c(-1.90691,0.76018,-0.26556,0.08571,NA)
> ceiling(x) [1] -1 1 0 1 NA
> floor(x) [1] -2 0 -1 0 NA
> trunc(x) [1] -1 0 0 0 NA
> round(x,1) [1] -1.9 0.8 -0.3 0.1 NA
> signif(x,2) [1] -1.900 0.760 -0.270 0.086 NA
> print(x,digits=1) [1] -1.91 0.76 -0.27 0.09 NA
> print(x,digits=2) [1] -1.907 0.760 -0.266 0.086 NA

# functions
> sum(x)
> prod(x) // product of all the elements
> cumsum(x) // cumulative sum
> cumprod(x) // cumulative product
> diff(x)
> diff(x, lag=2)

# factors
gender <- c(rep("female", 691), rep("male", 692))
gender <- factor(gender)
gender <- relevel(gender, ref="male")
gender <- factor(gender, levels=c("male", "female"))

No comments: