How to define a vector using R and perform simple arithmetic operations?

950    Asked by FujiwaraBan in Data Science , Asked on Jan 6, 2020
Answered by Fujiwara Ban

Vectors are the commonly used data objects used in R and there are many types as integer, logical, character, double, complex and raw.

Let us define some single element vectors to understand the concept

To define a character vector, we can do the following

print(‘xyz’)

To define a double vector, we can do the following

print(10.5)

To define a complex vector which contains real and imaginary number, we can do the following

print(2+5i)

To define a vector in R, we have to assign them to a variable.

v1=c(10,20,30)

v2=c(5,5,5)

Here, v1 and v2 are two variable having following vectors.

Now let us perform simple arithmetic operations

v1+v2 gives the following output

[1] 15 25 35

v1-v2 gives the following output

[1] 5 15 25

v1*v2 gives the following output

[1] 50 100 150

v1/v2 gives the following output

[1] 2 4 6

To check the class of a vector, we can use the following

class(v1)

[1] "numeric"

Hence the vector v1 is numeric in nature



Your Answer

Interviews

Parent Categories