Get to learn

Vectors in R for beginners

R is an object oriented program. In R, you work on objects like vectors, matrices, data frames etc. The simplest form of object in R is a vector. You can assign a value to a vector and give it any name.

(Note: R is case-sensitive. Thus, once you assign a particular name to a vector (or any other object like a matrix or a data frame and you want to use it again, you have to be careful to use the exact same name that you assigned. E.g. – you assigned a name vec to a vector, you cannot use Vec later, as v is in upper case and R would not recognize it)

Step 1: Assign a numerical value to a vector

Here we start with creating a vector and assigning a value to it. In this example, we will be working with share prices of different companies (imagined, mind you!). Let us say we observe the share prices of two companies i.e DLF and Grasim. The first thing we do is create a vector by their name.

Simply a) type the vector name b) type the arrow sign <- next to it and type the value you want to assign to the vector.

Vector name <- numerical value

Let us suppose the price of DLF is Rs 340 and that of Grasim is Rs 473

Type the following:

> DLF <- 340

> Grasim <- 473

Once you do this, you would want to check whether R has in fact created the vectors DLF and Grasim and assigned them the values. You would do this by simply typing the vector names one by one

If you simply type “DLF”

You get

DLF

[1] 340

This means that your friend R has created a vector by the name DLF and assigned a value to it. You would get a similar result if you type the other vector name i.e. Grasim.

Activity: Type the name Grasim and see the result

Step 2: Assign a character value to a vector

You wont always work with numerical values. In working with data, you will need to work with character values or what is known as String values. In R, you can assign a character value to a vector by simply typing the character (just the way you typed the numerical value in Step 1 and putting it within quotes.

Vector name <- “character value”

Lets say in our share price example, we want to specify that the currency that we are dealing with is Rupees, we create a vector Currency as below:

> Currency <- “Rupees”

As like before, if you want to cross check the vector Currency, you will simply type its name and get the following result

> Currency

[1] “Rupees”

Step 3: check the class of a vector

As we have seen a vector can have different classes. Class is like the nature of a vector – whether it is numeric or character. If you are given a vector and you want to check the class of that vector,

Use the function class() and simply write the name of the vector whose class you want to check

Functions perform well, functions for you. In R, there is a function for every action you want to perform on your data. Typically, the syntax of a function is function name(attributes). Attributes are nothing but inputs you need to give to the function for it to perform the job you want to it get done. They are of two kinds – one which are necessarily required to be specified by you. Other – if you don’t specify, their default values are assumed by R. In the class function, you need to specify the name of the vector whose class you are looking to identify.

Class(Vector name)

Thus, if you want to check the class of vectors you just created, type the syntax and the results will look like the following:

> class(DLF)

[1] “numeric”

> class(Grasim)

[1] “numeric”

> class(Denomination)

[1] “character”

Step 4: Assign multiple numerical values to a vector

Now, a vector can contain multiple values (a vector with a single value is actually a scalar). How do you assign multiple values to a vector. Simple: combine all the values within c() and separate them by a comma ,.

Note: the values assigned to a vector are also known as elements of the vector

Let us say we want to create a vector of daily earnings from a share on all days of the week (Monday to Friday since even share markets need a weekend off!)

Vector name <- c(value 1, value 2, value 3…)

In the following examples, we create the vector DLFearnings (mind the upper and lower case)

> DLFearnings <- c(10,15,-7,12,-3)

If you type DLFearnings, you get

> DLFearnings

[1] 10 15 -7 12 -3

Activity: assign values 8,6,14,-5 and 21 to a vector named Grasimearnings

Step 5: Assign multiple character values to a vector

This is similar to assigning numerical values, except for putting the character values withing quotes

Vector name <- c(“value 1”, “value 2”, “value 3”…)

Suppose you create a vector called Daynames and specify the names of the respective days, you will type:

Daynames <- c(“Monday”,”Tuesday”,”Wednesday”,”Thursday”,”Friday”)

Step 6: Assign the character values of one vector to numerical values of another vector

Let’s say you want to know that which values of DLFearnings belong to which day, that means you also want to name of the day to figure along with the earning value.

There are two ways to do it.

The longer way is to create a character vector, just like Daynames we created above and assign that vector to the vector DLFearnings by using the function names()

names(numeric vector) <- character vector

> names(DLFearnings) <- Daynames

The other way is to simply assign the day names to DLFearnings without creating the vector Daynames by using the names() function straightaway.

Which way is better? Well you certainly know which way is shorter! But the advantage of creating a separate character vector Daynames is that you can use it anywhere else you would want to later in your analysis. It just creates an object that can be used at a later stage, otherwise, you will always have to type the day names all over again. Lets say now you also want to assign the same names to DLF earnings. If you already have created the vector Daynames, you would simply assign the same to Grasimearnings by typing:

> names(Grasimearnings) <- Daynames

You can always check your vectors to know whether your desire of attaching the week names has been fulfilled

> DLFearnings

Monday Tuesday Wednesday Thursday Friday

10 15 -7 12 -3

> Grasimearnings

Monday Tuesday Wednesday Thursday Friday

8 6 14 -5 21

Step 7: Add two vectors

Now what if you want to know your daywise total earnings. Remember,we are talking daywise and not the total earning of the week. The important thing to remember here is that if you add two vectors, each element of the vector gets added to the corresponding vector.

Thus if you want to add DLFearnings and Grasimearnings and attribute the results to a vector named Dailyaernings (again creating a separate vector of the result will help in using it as an object at a later stage), you will type:

> Dailyearnings <- DLFearnings + Grasimearnings

> Dailyearnings

Monday Tuesday Wednesday Thursday Friday

18 21 7 7 18

(Monday value of DLFearnings will be added to Monday value of Grasimearnings)

Syntax:

New vector <- vector1 + vector2

Step 8: Find sum of all elements of the vector

If we want to add up all the elements of a vector, we use the function sum()

sum(vector name)

If you want to find out the total weekly earning from DLF and assign it to a new vector Totaldlf (you know why!), you will type:

> Totaldlf <- sum(DLFearnings)

For seeing the actual result type the name of the new vector:

> Totaldlf

[1] 27

Activity: find the total weekly earning in Grasim and assign the value in Totalgrasim

If you now want to see total week’s earnings including DLF and Grasim, you simply add the two vectors and store the result in a new vector Totalweek

> Totalweek <- Totaldlf + Totalgrasim

See the actual value:

> Totalweek

[1] 71

Step 9: Compare two vectors

If you have two vectors with a numeric value and you want to compare which one has the bigger value, you use the < or > sign. The result will be in the form of TRUE or FALSE

If you want to ompare total earnings between DLF and Grasim

> Totaldlf > Totalgrasim

[1] FALSE

Step 10: Select a particular element of a vector

This is a very important concept in R, selecting a particular element of a set of elements from a vector. It is also known as subsetting.

What we want to do is select an element from a vector and assign it to another vector (for guess what, future use!)

For subsetting, we use the square brackets []

New vector <- old vector[position of the element in the vector/name of the element]

If you want to see the earnings on Tuesday in DLF, type:

> Dlfbest <- DLFearnings[2]

> Dlfbest

Tuesday

15

What if you want to select elements placed apart in a vector. Use c()

If you want to see Wednesday and Friday’s earnings in Grasim, type:

> Bestgrasim <- Grasimearnings[c(3,5)]

> Bestgrasim

Wednesday Friday

14 21

As said earlier, apart from mentioning position of the elements to be selected, we can also mention the names of such elements

> SGrasim <- Grasimearnings[c(“Monday”,”Thursday”)]

> SGrasim

Monday Thursday

8 -5

Step 10: Compare elements of a vector based on value

If you want to find out, on which days you earning more than or equal to Rs 12, type:

> Greatdays <- DLFearnings >=12

> Greatdays

Monday Tuesday Wednesday Thursday Friday

FALSE TRUE FALSE TRUE FALSE

Now you will see the utility of assigning the above elements to a vector. The above only gives you days on which earnings were above Rs 12 but does not give the actual earnings.

For this, you will subset the Greatdays vector within the DLF earnings and store it in another vector

> Greatreturn <- DLFearnings[Greatdays]

> Greatreturn

Tuesday Thursday

15 12

Activity: Check on which days we earned more than 12 in Grasim

The aim of this article was to get you going with vectors in R and give you some confidence in working with R. Happy Ring.