Names Function in R Basics-Quick Guide

Names Function in R, In this post, we’ll look at how to use the names () function to give vectors and lists names.

Syntax

Basic R Syntax of names function is names (x)

Example 1: Assign Names to Vector

Let’s create a vector and assign the name.

vector <- 1:10                     # Sample vector values from 1 to 10.
vector                             # Print the values stored in vector
# 1 2 3 4 5 6 7 8 9 10

There are ten elements in the output that have no names. We can now give each element a name while using names and letter functions.

names(vector) <- letters[1:10]     # Assign names to vector
vector                             # Print the values stored in modified vector
      a  b  c  d  e  f  g  h  i  j
      1  2  3  4  5  6  7  8  9 10

The previous R syntax assigned the alphabetic letters a, b, c, d, e, f, g, h, i, and j as names to our vector elements.

How to check the names of vector?

Let’s run the code names(vector)

names(vector)                     # Return names of vector
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

How to clean the datasets in R? » janitor Data Cleansing »

Example 2: Assign Names to List

In the same approach, we may make a list of names. To begin, make a list and store some values.

list <- list(1:10,3,"abc")
list  ## print the stored values in the list
[[1]]
 [1]  1  2  3  4  5  6  7  8  9 10
[[2]]
[1] 3
[[3]]
[1] "abc"

Now you can see the above list contained 3 elements without any names.

Let’s assign some names to that.

names(list) <- LETTERS[1:3]    # Assign names to list
list                           # Print the modified list
$A
 [1]  1  2  3  4  5  6  7  8  9 10
$B
[1] 3
$C
[1] "abc"

Yes, now three elements named A, B and C. Let’s check the same using the names function.

names(list)                   
# "A" "B" "C"

LSTM Network in R » Recurrent Neural network »

You may also like...

Leave a Reply

Your email address will not be published.

error

Subscribe Now