13.2 C
London
Tuesday, July 2, 2024
HomeStatistics TutorialRHow to Create an Empty Vector in R (With Examples)

How to Create an Empty Vector in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use one of the following methods to create an empty vector in R:

#create empty vector with length zero and no specific class
empty_vec #create empty vector with length zero and a specific class
empty_vec #create empty vector with specific length
empty_vec 10)

The following examples show how to use each of these methods in practice.

Method 1: Create Empty Vector with Length Zero

The following code shows how to create a vector with a length of zero and no specific class:

#create empty vector with length zero and no specific class
empty_vec #display length of vector
length(empty_vec)

[1] 0

We can then fill the vector with values if we’d like:

#add values 1 through 10 to empty vector
empty_vec #view updated vector
empty_vec

[1]  1  2  3  4  5  6  7  8  9 10

Method 2: Create Empty Vector of Specific Class

The following code shows how to create empty vectors of specific classes:

#create empty vector of class 'character'
empty_vec 

[1] "character"

#create empty vector of class 'numeric'
empty_vec #create empty vector of class 'logical'
empty_vec 

Method 3: Create Empty Vector with Specific Length

The following code shows how to create a vector with a specific length in R:

#create empty vector with length 10
empty_vec 10)

#display empty vector
empty_vec

[1] NA NA NA NA NA NA NA NA NA NA

If you know the length of the vector at the outset, this is the most memory-efficient solution in R.

Additional Resources

How to Create an Empty List in R
How to Create an Empty Data Frame in R
How to Convert List to Vector in R
How to Convert Data Frame Column to Vector in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories