In this article, we are going to see how to extract just the number from the named numeric vector in R Programming Language.
Method 1: Using NULL
The names() method can be invoked on the vector and assigned to NULL in order to remove any instances of the names set to this object. It makes modifications to the original vector object.
# declaring a vector vec <- c (0 : 5)
# assigning names to the vector names (vec)<- c ( "Ele1" , "Ele2" , "Ele3" ,
"Ele4" , "Ele5" , "Ele6" )
print ( "Original vector" )
print (vec)
# assigning the names vector to null names (vec) <- NULL
print ( "Modified vector" )
print (vec)
|
Output:
[1] "Original vector" Ele1 Ele2 Ele3 Ele4 Ele5 Ele6 0 1 2 3 4 5 [1] "Modified vector" [1] 0 1 2 3 4 5
Explanation: The string names have been assigned as names to the corresponding elements of the vector. As soon as null is assigned to the names() method, the names are reset, and only the numerical values are returned.
Method 2: Using unname() method
unname() method in R is used to remove any instances of the names assigned to the R object over which it is invoked. It resets the names assigned to the vector object and extracts the numeric portion from it. The changes have to be stored in order to make them reflect during further usage.
# declaring a vector vec <- c (0 : 5)
# assigning names to the vector names (vec)<- c ( "Ele1" , "Ele2" ,
"Ele3" , "Ele4" , "Ele5" )
print ( "Original vector" )
print (vec)
# assigning the names vector to null vec_mod <- unname (vec)
print ( "Modified vector" )
print (vec_mod)
|
Output:
[1] "Original vector" Ele1 Ele2 Ele3 Ele4 Ele5 <NA> 0 1 2 3 4 5 [1] "Modified vector" [1] 0 1 2 3 4 5
Method 3: Using as.numeric() method
The as.numeric() method in R is used to coerce an argument to a numerical value. However, it’s a generic function applicable to both integers, float, or double type numbers. It eliminates any strings stored within the numbers, be it names or elements that are not convertible to numeric data. The changes have to be stored in order to make them reflect during further usage.
as.numeric(x)
# declaring a vector vec <- c (1.2, 35.6, 35.2, 0.9, 46.7)
# assigning names to the vector names (vec)<- c ( "Ele1" , "Ele2" ,
"Ele3" , "Ele4" , "Ele5" )
print ( "Original vector" )
print (vec)
# reassigning names vec_mod <- as.numeric (vec)
print ( "Modified vector" )
print (vec_mod)
|
Output:
[1] "Original vector" Ele1 Ele2 Ele3 Ele4 Ele5 1.2 35.6 35.2 0.9 46.7 [1] "Modified vector" [1] 1.2 35.6 35.2 0.9 46.7