Open In App

How to create a new vector from a given vector in R

Last Updated : 16 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss How to create a new vector from a given vector in R Programming Language.

Create a new vector from a given vector

You can use various functions and techniques depending on your needs to create a new vector from a given vector in R. Here are some common methods.

1. Subset the Vector

If you want to create a new vector with specific elements from an existing vector, you can use indexing or logical conditions.

R
# Original vector
original_vector <- c(1, 2, 3, 4, 5)

# Create a new vector with specific elements (e.g., elements at index 2 and 4)
new_vector <- original_vector[c(2, 4)]
new_vector

Output:

[1] 2 4

2. Using Functions

Use functions like subset() or filter() from packages like dplyr to create a new vector based on certain conditions.

R
# Using dplyr package
library(dplyr)

# Original vector
original_vector <- c(1, 2, 3, 4, 5)

# Create a new vector with elements greater than 2
new_vector <- subset(original_vector, original_vector > 2)
new_vector

Output:

[1] 3 4 5

3. Applying Functions

You can apply functions to each element of a vector using sapply() or lapply() and store the results in a new vector.

R
# Original vector
original_vector <- c(1, 2, 3, 4, 5)

# Create a new vector with squared elements
new_vector <- sapply(original_vector, function(x) x^2)
new_vector

Output:

[1]  1  4  9 16 25

4.Combining Vectors

Combine multiple vectors to create a new vector using functions like c().

R
# Original vectors
vector1 <- c(1, 2, 3)
vector2 <- c(4, 5, 6)

# Create a new vector by combining vector1 and vector2
new_vector <- c(vector1, vector2)
new_vector

Output:

[1] 1 2 3 4 5 6

Conclusion

Vectors in R offer efficient data handling, simplification of code, and support for bulk operations in mathematical and statistical analysis. However, they have limitations such as homogeneous data type requirement, potential memory usage concerns, indexing complexity, and limited support for complex data structures. Overall, vectors are a powerful tool for many data manipulation tasks but may require careful consideration of their constraints in certain scenarios.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads