R – Create empty vector and append values
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:
R
a= c ()
print (a)
a=1:20
print (a)
|
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:
R
a= c ()
print (a)
a= c ( 'sravan' , 'bobby' , 'rohith' , 'gnnaesh' , 'gajji' )
print (a)
|
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:
R
a= c ()
print (a)
b= c ()
print (b)
d= c ()
print (d)
a[1]=10
a[2]=20
a[3]=14.5
a[4]=89.000
print (a)
b[1]= TRUE
b[2]= FALSE
b[3]= FALSE
print (b)
d[1]= "Sravan"
d[2]= "Bobby"
d[3]= "pinkey"
print (d)
|
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:
R
a= c ()
print (a)
a[1]= "sravan"
a[2]=20
a[3]=14.5
a[4]= FALSE
print (a)
|
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:
R
a= c ()
print (a)
a= append (a,10)
print (a)
|
Output:
NULL
[1] 10
We can also append multiple data using c() function
Syntax:
append(vector,c(value1,value2,.value n))
Example:
R
a= c ()
print (a)
a= append (a, c (1:10))
print (a)
|
Output:
NULL
[1] 1 2 3 4 5 6 7 8 9 10
Last Updated :
29 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...