> # VECTORS > x<-c(1,3,2,10,5) #create a vector x with 5 components > y<-1:5 #create a vector of consecutive integers > x [1] 1 3 2 10 5 > y [1] 1 2 3 4 5 > y+2 #scalar addition [1] 3 4 5 6 7 > 2*y #scalar multiplication [1] 2 4 6 8 10 > y^2 #raise each component to the second power [1] 1 4 9 16 25 > 2^y #raise 2 to the first through fifth power [1] 2 4 8 16 32 > y #y itself has not been unchanged [1] 1 2 3 4 5 > y<-y*2 > y #it is now changed [1] 2 4 6 8 10 > x<-c(1,3,2,10,5); y<-1:5 #two or more statements are separated by semicolons > y [1] 1 2 3 4 5 > x+y [1] 2 5 5 14 10 > x*y [1] 1 6 6 40 25 > x/y [1] 1.0000000 1.5000000 0.6666667 2.5000000 1.0000000 > x^y [1] 1 9 8 10000 3125 > sum(x) #sum of elements in x [1] 21 > cumsum(x) #cumulative sum vector [1] 1 4 6 16 21 > diff(x) # first difference [1] 2 -1 8 -5 > diff(x,2) #second difference [1] 1 7 3 > max(x) #maximum [1] 10 > min(x) #minimum [1] 1 > x [1] 1 3 2 10 5 > sort(x) # increasing order [1] 1 2 3 5 10 > sort(x, decreasing=T) # decreasing order [1] 10 5 3 2 1 > > # COMPONENT EXTRACTION > > x [1] 1 3 2 10 5 > length(x) # number of elements in x [1] 5 > x[3] # the third element of x [1] 2 > x[3:5] # the third to fifth element of x, inclusive [1] 2 10 5 > x[-2] # all except the second element [1] 1 2 10 5 > x[x>3] # list of elements in x greater than 3 [1] 10 5 > > # LOGICAL VECTOR > > x>3 [1] FALSE FALSE FALSE TRUE TRUE > as.numeric(x>3) # as.numeric() function coerces logical components to numeric [1] 0 0 0 1 1 > sum(x>3) # number of elements in x greater than 3 [1] 2 > (1:length(x))[x<=2] # indices of x whose components are less than or equal to 2 [1] 1 3 > z<-as.logical(c(1,0,0,1)) # numeric to logical vector conversion > z [1] TRUE FALSE FALSE TRUE > > # CHARACTER VECTOR > > colors<-c("green", "blue", "orange", "yellow", "red") > colors [1] "green" "blue" "orange" "yellow" "red" > > # VECTOR COMPONENTS CAN BE NAMED > > names(x) # check if any names are attached to x NULL > names(x)<-colors # assign the names using the character vector colors > x green blue orange yellow red 1 3 2 10 5 > x["green"] # component reference by its name green 1 > names(x)<-NULL # names can be removed by assigning NULL > x [1] 1 3 2 10 5 > > # CONSTRUCT VECTORS WITH PATTERNS > > 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,20,length=5) [1] 0 5 10 15 20 > seq(0,1,by=0.1) [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 > rep(1,3) [1] 1 1 1 > c(rep(1,3),rep(2,2),rep(-1,4)) [1] 1 1 1 2 2 -1 -1 -1 -1 > rep("Small",3) [1] "Small" "Small" "Small" > c(rep("Small",3),rep("Medium",4)) [1] "Small" "Small" "Small" "Medium" "Medium" "Medium" "Medium" > rep(c("Low","High"),3) [1] "Low" "High" "Low" "High" "Low" "High" > q()