Thursday, October 20, 2011

R - Cheat sheet - Vectors

Return to the R Cheat sheet main index page

Create a vector. (Note the c)
> x<-c(1,2,5,9,15)
> x
[1]  1  2  5  9 15


Create a vector with elements of consecutive integer values.
> x<-1:7
> x
[1] 1 2 3 4 5 6 7

> x<-1:10
> x<-x*2
> x
 [1]  2  4  6  8 10 12 14 16 18 20


Some commands
min(x) - minimum of the elements in x.
max(x) - maximum of the elements in x.

sort(x)
sort(x, decreasing=T)
> y<-c(5,8,2,0,2)
> sort(y, decreasing=T)
[1] 8 5 2 2 0


length(x) - length of vector
x[n] - get nth element from vector. first element is position 1, not position 0.
x[3:7] - get range of elements

> x<-1:10
> x
 [1]  1  2  3  4  5  6  7  8  9 10
> x[3:7]
[1] 3 4 5 6 7

x[-5] Get all elements from the vector except the 5th element.

x[x>5]  Get the elements whose values are greater than 5.

x > 5 Show which elements in the vector have values greater than b5.

> x
 [1]  1  2  3  4  5  6  7  8  9 10
> x> 5
 [1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE


Creating sequences
seq(n)


> seq(10)
 [1]  1  2  3  4  5  6  7  8  9 10
> seq(0,1,length=10)
 [1] 0.0000000 0.1111111 0.2222222 0.3333333 0.4444444 0.5555556 0.6666667
 [8] 0.7777778 0.8888889 1.0000000
> seq(0,1,by=0.2)
[1] 0.0 0.2 0.4 0.6 0.8 1.0


No comments:

Post a Comment