Open In App

Assigning Vectors in R Programming

Vectors are one of the most basic data structure in R. They contain data of same type. Vectors in R is equivalent to arrays in other programming languages. In R, array is a vector of one or more dimensions and every single object created is stored in the form of a vector. The members of a vector are termed as components .



Assigning of Vectors

There are different ways of assigning vectors. In R, this task can be performed using c() or using “:” or using seq() function.

Assigning Named Vectors in R

It’s also possible to create named vectors in R such that every value has a name assigned with it. R provides the names() function in order to create named vectors.

Example:

Suppose one wants to create a named vector with the number of players in each sport. To do so, first, he will create a numeric vector containing the number of players. Now, he can use the names() function to assign the name of the sports to the number of players.




# R program to illustrate
# Assigning named vectors
  
# Creating a numeric vector
# with the number of players
sports.players = c(2, 4, 5, 6, 7, 9, 11)
  
# Assigning sports name to the numeric vector
names(sports.players) = c("Bridge", "Polo", "Basketball"
                          "Volleyball", "kabaddi"
                          "Baseball", "Cricket")
  
# Displaying the named vector
print(sports.players)

Output:

 Bridge   Polo   Basketball  Volleyball  kabaddi   Baseball    Cricket 
  
    2      4            5           6        7          9         11 

In order to get a sport with a particular number of players:




# Displaying the sports with 9 players
print(names(sports.players[sports.players==9]))
  
# Displaying the sports with 1 player
print(names(sports.players[sports.players==1]))

Output:

"Baseball"
character(0)

Explanation:

Baseball has nine players so it displays Baseball as output. Since here there is no sport with one player in this named vector, no output is generated and it displays the output as the character(0). 

Access elements of a vector

In R in order to access the elements of a vector, vector indexing could be performed.

Note: Please note that indexing in R begins from 1 and not 0.

Example 1: 




# R program 
# To access elements
  
# Creating a vector by seq() function
V = seq(1, 40, by= 4)
  
# Printing the vector
print(V)
  
# Printing the fifth element of the vector
print(V[5])

Output:

[1] 1  5  9 13 17 21 25 29 33 37
[1] 17

Example 2: 




# R program 
# To access multiple elements
  
# Creating a vector by seq() function
V = seq(1, 40, by= 4)
  
# Printing the vector
print(V)
  
# Printing the fifth and seventh element of the vector
print(V[c(5,7)])

Output:

[1] 1  5  9 13 17 21 25 29 33 37
[1] 17 25

Article Tags :