Friday 3 April 2015

Learn Vectors 2


We will learn:

1. Vector Names
2. Plotting One Vectors

Details:

This is part two of learning vectors in R programming language. If you haven't learned about the first part, you can start to learn vectors part one.

D. Vector Names


For instance, I have three values (e.g. red, yellow and black) which is stored in wordlist c vector. That will be written as follows;

wordlist <- c("red","yellow","black")    # wordlist stored "red", "yellow" and "black" value.

As explained in Vector Access, when you need to pick one of the values, you can do like this:

rank[1:3]
Result: [1] "red","yellow","black"

Now, this time we will learn that "we can assign names to a vector's elements by passing a second vector filled with names to the "names" assignment function".(taken from. http://tryr.codeschool.com/levels/2/challenges/18) , as in:

names(wordlist) <- c("red","yellow","black")

(Note: to see more about names function in R, type:
help(names)
)

When we want to access or pick one of the values, we can type like this:

wordlist["yellow"]
Result: yellow
      2

From the example above, that means, that we can access the value directly beside our common way, as in:

wordlist[2]

Result: yellow
      2

From here, we also can change the position of "yellow" (that is: 2) to other position, for example, 7.

wordlist["yellow] <- 7

Now, see if it already changes:

wordlist["yellow"]
Result: "7"

or, with other way;

wordlist[7]
Result: "yellow"

E. Plotting One Vector


This section, we will learn about barplot. What is it? barplot is R function which is used to create vertical or horizontal bars (e.g. chart) with vector values. For further and details about that, just ask R to answer by typing: -

help(barplot)

Hint: Talking about Vectors will force you to remember 2 things: Variables and Values.

For example, we have ( again and again ... :p ) three values in c vector, they are: 3, 5 and 1, as follows:
1. Variable : stuDentS (warning: case sensitive!)
2. Value:  3, 5, 1.

in R, as usual, you can type:

stuDentS<- c(3,5,1)

Then, let's start using barplot (hurrayyyy):

barplot(stuDentS)

Done! R will give us this amazing result!!!


Barplot in R Programming


Further, if you assign new names in the vector values (... say, barney, herman and adhya), R will take it as Labels which will be placed below each bars based on the order you give.
For example:

names(stuDentS)<-c("Aminah","Herman","Adhya")

Then, R will give you this awesome chart!


Barplot in R Programming


Now, to show other types of chart, you can give range from 1 through 100, as in:

barplot(1:100)

Here's the result:




See you on the next lesson :D, my best regards.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home