Tuesday, July 7, 2015

R programming - Vectors

Refer index page for R at the following URL:
http://mylearningcafe.blogspot.in/2015/07/r-programming-index-page.html

Vectors are important data types in R.
Vectors can be thought of as a list of items of any data type. However, it cannot contain a mix of data types. Thus, you could have a vector of numerics, string etc but not a mix.

How to define or create a vector?
Vectors are created using the c (...) command

Thus to create a vector of 3 items (1,2,3) we need to run the following command

x<-c(1,2,3)
x<-c("Hi","how","are","you","?")




One cool feature is that we can create a vector of large numbers by providing a range

x<-c(1:5) or x<-1:5
This will create a vector of 5 elements

We can also create a list of negative values if needed



Another cool option that R provides in Vectors is that we can do mathematical operations on all the elements in a vector.

x<-1:3
x*2




One can also add/subtract same length vectors



What happens if the length differs?
In such a case, the function will be applied till the length matches, then an error is thrown.

Lets have 2 vectors
x<1:3  (length =3)
z<-1:5 (length =5)
x+z will add the first 3 elements and then throw an error




How to check length of a list?
Use the length command

length(x)



How to get specific elements from a list?
Use the command list_name[char number]

x[2]
z[1:3] will return first 3 elements



Check for elements within a Vector?

Checks are performed for each element of a vector.

x<-1:5
x<=2 will return TRUE TRUE FALSE FALSE FALSE

We also have any and all commands

any(x<3) will look if any element is less than 3 and return TRUE/FALSE. In this case, TRUE is returned.

all(x<3) will look if all elements are less than 3 and return TRUE/FALSE. In this case, FALSE is returned.



  
Refer index page for R at the following URL:
http://mylearningcafe.blogspot.in/2015/07/r-programming-index-page.html

No comments:

Post a Comment