R is a free programming language mainly used for statistical computing and graphics. R is an interpreter similar to Python where you don’t have to compile first in order to run your program. Once you create your program you can just run it on a wide variety of UNIX platforms, Windows and MacOS.
R was initially started by statisticians to make statistical processing easier but later other programmers are involved and evolved it to a wide variety of non-statistical tasks, including data processing, graphic visualization, and analytical processing.
1. What is R Vector?
The vector in R is the simplest basic type of object in R. A vector is a sequence of data elements of the same type. A vector is similar to a sequence object in Python pandas. Members of a vector are called Components. Below are some key points to note and remember about vectors.
- Vector is a basic data structure in R.
- It is a one-dimensional data structure.
- It holds elements of the same type.
- Members in the vector are called components.
- It is not recursive.
- We can easily convert vectors into data frames or matrices.
- In DataFrame, each column is considered a vector.
2. Create Vector
Let’s create a simple integer vector using
c(). Note that the
c() function stands for concatenate. but it is one of the most used ways to create a vector in R.
# Integer vector v_int = c(1,3,6,7) print(v_int) # Output # 1 3 6 7
And, you can also use this to create a character vector. Alternatively, you can also use the character() function.
# Character vector v_char = c('One','Two','Three') print(v_char) # Output # "One" "Two" "Three"
length() function to get the length of the vector. Pass the vector as the argument to this function to get the length.
# Length of the vector length(v_char) # Output # 3
You can get the type of the vector using
typeof() function. This takes the vector object as an argument and returns its type.
# Type of the vector typeof(v_char) # Output  "character"
If you have a character vector, you can easily convert the character vector to double by using
as.vector() function with a
# Syntax of as.vector() as.vector(x, mode = "any")
# Convert character vector to double x <- c("1","2") print(typeof(x)) x <- as.vector(x,"numeric") print(typeof(x)) # Output # "character" # "double"
is.vector() to check the type of the vector a specific type.
# Syntax of is.vector() is.vector(x, mode = "any")
# Check type of vector x <- c("1","2") is.vector(x,'character') is.vector(x,'numeric') # Output  TRUE  FALSE
3. Empty Vector
If the length of the vector is zero then it is considered an empty vector in R. It can be created in several ways in R programming. One way to create an empty vector is by using
c() function without any arguments.
# Create empty vector v_empty = c() print(v_empty) # Output NULL
Now let’s get the length of the vector and check if it is empty.
# Length of the vector length(v_empty) # Output # 0
4. Convert Vectors into DataFrame
data.frame() function we can create a DataFrame from Vectors. A data frame is a list of variables of the same number of rows with unique row names. so all vectors you used to convert to DataFrame should have the same length, not having the same length will result in an error.
# Create Vectors id <- c(10,11,12,13) name <- c('sai','ram','deepika','sahithi') dob <- as.Date(c('1990-10-02','1981-3-24','1987-6-14','1985-8-16')) # Create DataFrame df <- data.frame(id,name,dob)
Yields below output. In the above example, I have used the vectors
dob as arguments to the
data.frame() function, separated by commas. The above example yields the below output. R will create a data frame with the column names/variables with the same names we used for Vector. You can use
print(df) to print the DataFrame to the console.
# Output id name dob 1 10 sai 1990-10-02 2 11 ram 1981-03-24 3 12 deepika 1987-06-14 4 13 sahithi 1985-08-16
6. Repeating Vectors
rep() function we can repeat the members in a vector with the specified number of
times, and create a new vector with the result.
# Repeat vectors v_rep = rep(c(1, 5), times = 3) print(v_rep) # Output # 1 5 1 5 1 5
Let’s pass a vector to times and see what happens. This is used to specify how often the values are to be repeated. You can also use
each argument to specify how many times to repeat each value.
# Repeat vectors v_rep = rep(c(1, 5), times = c(2,3)) print(v_rep) # Output # 1 1 5 5 5
7. Types of Vector in R
You can create a vector with all basic types.
- Integer Vectors – Stores only integer values.
- Numeric Vectors – For all numeric values.
- Character Vectors – Stores alphanumeric characters.
- Logical Vectors – Stores TRUE/FALSE values.
- Datetime Vectors – Which are used to store date time values
- Factor Vectors – To work with categories.
8. Combine Two or Multiple Vectors
As explained above
c() is actually used to combine members hence, let’s use this to combine two or more vectors into a single vector. By using c() or append() you can also add element to vector in R.
# Create character vectors v_char = c('One','Two','Three') v_char2 = c('Four','Five','Six') # Combine vectors v_combine = c(v_char,v_char2) print(v_combine) # Output # "One" "Two" "Three" "Four" "Five" "Six"
9. Access Vector
By using R bracket notation you can access the members by index. Note that, unlike other programming languages, the R index starts from
1. To get the range of values use
startindex:endindex, this returns all values between the start and end index. Let’s access it by giving an index inside a single square bracket
# Access vector elements v_char # Returns  "One" v_char[1:3] # Returns  "One" "Two" "Three"
When you use a negative index, it just removes the specified index vector and returns the result. For example, the following creates a vector slice with the second member removed.
# Access vector elements v_char2 = c('Four','Five','Six') v_char2[-2] # Output # "Four" "Six"
If an index is used that is not present,
NA is returned as a result.
# Access vector elements v_char2 # Output # NA
10. Change Values in Vector
By using an index let’s see how to modify or change the value of an index. The following example changes the value of the first member of the vector to the character string
# Change vector elements v_char <- "Oneeeeeeee" print(v_char) # Output  "Oneeeeeeee" "Two" "Three"
11. R Vectors vs list
Below are some differences between vector vs list.
- Vector can hold only elements of the same type. whereas the List can hold elements of different types like numeric, character, logical e.t.c
- Vector is a single dimension, whereas the List is a multi-dimensional object.
- Vector is not recursive, whereas the List is recursive.
# Create list list_obj = list('One',2,TRUE) print(list_obj) # Output[] #[] # "One" #[] # 2 #[] # TRUE
12. Handling NA Values in R Vector
NA is considered a ‘Missing Values’ or ‘Not Available’ in R and to remove NA values from the vector use
is.na() functions. Additionally R also supports several other methods to delete
NA from the vector.
When you run an arithmetic operation on the R vector that has NA values, you will get results as NA. In general, any operation on an NA becomes a NA. hence, It’s best practice to clean up the vector by removing all NA values before performing an arithmetic operation.
# Quick Examples # Create Vector ids <- c(10,5,NA,15,10) # Using is.na() x <- ids[!is.na(ids)] # Using na.rm=TRUE x <- max(ids, na.rm=TRUE) # Using na.omit() x <- na.omit(ids) # Remove NA from string Vector. states = c('NY','DC',NA,'CA','NV',NA) x <- na.omit(states) # Using exclude x <- na.exclude(states) print(x)
13. Sorting Vectors
To sort a vector alphabetically using the
sort() function that takes a vector as an argument and returns an alphabetically ordered value for the character vector and ascending order for numeric.
# Sort Character Vector v <- c('D','R','G','A','X') sort(v) sort(v, decreasing=TRUE) # Output #> sort(v) # "A" "D" "G" "R" "X" #>sort(v, decreasing=TRUE) # "X" "R" "G" "D" "A"
14. Subsetting Vectors
To subset elements from the vector use bracket notation , by using this notation we can subset a single element from a vector, multiple elements, and subset by range, select elements from a list e.t.c.
# Create a vector v <- c('A','B','C','D','E','F') # Subset by Index Position v # Output #> v # "A" # Subset elements from list v[c(1,3)] v[c(2.3,4.5)] # Output #> v[c(1,3)] # "A" "C" #> v[c(2.3,4.5)] # "B" "D"
15. Removing Duplicates
Handling duplicate values is one of the challenging tasks when analyzing data. Removing duplicates comes under data cleaning which is a challenging task in data analytics. Data cleaning needs to be done before performing any operations on data as having duplicate values results in inconsistent results. In the R vector, By using
duplicated() function we can remove duplicates from the vector.
Remove duplicates v <- c('A','B','D','C','A','F','G','C','d','E','E') v[!duplicated(v)] # Output # "A" "B" "D" "C" "F" "G" "d" "E"
16. Remove Elements
To remove multiple values from a vector, define a vector or list with the values you wanted to remove and use it with bracket notation  and %in% operator. The %in% operator is used to check what values to remove.
# Remove specific value from vector x <- c('A','B','C','D','E','F','B') x[ !x == 'A'] # Output # "B" "C" "D" "E" "F" "B" # Remove Multiple Values x <- c('A','B','C','D','E','F','B') x[! x %in% c('A', 'D', 'E')] # Output # "B" "C" "F" "B"
In this article, you have learned what is the vector in R? The vector is a basic one-dimensional data structure, It holds elements of the same type. Members in the vector are called components. It is not recursive and we can easily convert vectors into data frames or matrices.
Also, learned the differences between lists. Vector can hold only elements of the same type. whereas the List can hold elements of different types like numeric, character, logical e.t.c Vector is a single dimension, whereas the List is a multi-dimensional object. Vector is not recursive, whereas the List is recursive.
You can find several examples of R vectors at Github R Programming Examples Project.
- Explain Character Vector in R?
- How to Get Vector Length in R?
- Add or Append Element to Vector in R?
- How to Remove NA from Vector?
- How to Create a Vector in R?
- How to Create a DataFrame From Vectors?
- How to Create Empty Vector in R?
- Create Character Vector in R?
- How to Convert Vector to List in R?
- How to Convert List to Vector in R?
- How to Concatenate Vector in R?
- Merge Vector Elements into String in R?
- How to Subset Vector in R?
- How to Sort Vector in R?
- How to Convert List to String?