VOOZH about

URL: https://www.geeksforgeeks.org/r-language/r-create-empty-vector-and-append-values/

⇱ R - Create empty vector and append values - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

R - Create empty vector and append values

Last Updated : 29 Jul, 2021

In this article, we will discuss how to create an empty vector and add elements into a vector in R Programming Language. An empty vector can be created by simply not passing any value while creating a regular vector using the c() function.

Syntax:

c()

This will return NULL as an output.

Example:

Output:

NULL

A nested empty vector can also be created in R programming language.

Example:

Output:

NULL

Adding values to an empty vector

Method 1: Using range

We can use range (:) operator to add elements to an empty vector

Syntax:

start_value:end_value

Example:

Output:

NULL
 [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

Method 2: Using another vector

For this a vector is first created empty and then a vector is assigned to it.

Example: 

Output:

NULL
[1] "sravan" "bobby" "rohith" "gnnaesh" "gajji" 

Method 3: Using index

We can assign/fill values in an empty vector by using "[]" operator which is known as the index operator

Syntax:

vector_name[index_location]=data

where, vector_name is the name of the empty vector which is created

  • Index_location is the index value where particular element is located
  • Data is the value which is assigned to particular index location

Example 1:

Output:


 

NULL
NULL
NULL
[1] 10.0 20.0 14.5 89.0
[1] TRUE FALSE FALSE
[1] "Sravan" "Bobby" "pinkey"


 

We can insert all types of vectors in one empty vector.


 

Example 2:


 

Output:

NULL
[1] "sravan" "20" "14.5" "FALSE" 

Method 4: Using append()

We can add data by using the append() function.

Syntax:

append(vector_name,value)

Where, vector_name is the name of the vector and value is the input value.

Example:

Output:

NULL
[1] 10

We can also append multiple data using c() function

Syntax:

append(vector,c(value1,value2,.value n))

Example:

Output:

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

Explore