######################################################### # EXAMPLE 1: using variables # In R we think of variables as 'objects' # A object has a name a structure a value or # several data values # ######################################################### # a simple scalar variable for integer numbers i<-1 # our first function call: print() can print a kinds of objects # and it will do different things with different ojects, as you see print(i) # a 1-dimensional array = vector filled with integers # with the concatenate function c() you can create vectors index<-c(1,2,4,8,16) print (index) # you can also paste thigns together into a text string text1<-paste("i=",i) text2<-paste("index=",index) print(text1) print(text2) # But that is not what we wanted # We see that is assuming it has to perform the pasting with all values in the vector # and you can combine functions: i.e use the returned value to feed to a second function # Here we use paste() inside print() # note the last optional parameter in paste(): see a difference? print(paste('i=',i,sep='')) # now we use a conversion of the vector with integer number into text string # with as.character() clumsy<-paste(index,collapse=',') print(paste('index=',clumsy)) # R is recyling values: look at this way to fill a vector index2<-rep(index,2) clumsy<-paste(index2,collapse=',') print(paste('index2=',clumsy)) ############################################################### # here is one of the most essential programming structures # flow control depending on some statement that can be either TRUE or FALSE # 'if then else that' ############################################################### if (i>0) { i<-i-1 } else { i<-i+1 } # if your lines get too long in the code just break it up # BUT not inside the string (inside " " or ' ') print (paste("what happened to your initial i? ", "Now i=",i,sep='')) # okay next we will learn the most essential options to select # subsets from a vector # use [] to access data # here we wnat to get element at position 4 print(paste("index[4]=",index2[4])) ################################################################ # try to uncomment this one here and see what happens ################################################################ #print(paste("index[0]=",index2[0])) print(paste("index[20]=",index2[20])) # HENCE: BE CAREFUL THAT YOUR INDEX RANE IS VALID, OTHERWISE # UNEXPECTED THINGS CAN HAPPEN # make sure it is in the range of 1... length(index2) print(paste("index[2:3]",index[2:3])) # and here is something complex but later very useful # we can pick conditionally isbig<-index2>4 print(paste("Big numbers in index:",paste(index2[isbig],collapse=','))) ######################################################################## # next we will look at matrices and general arrays # data frames and lists ########################################################################