In this article, we will discuss the difference between setNames and setnames methods with examples in R Programming language.
setNames:
setNames is available in stats package, used to name the elements in a vector.
Syntax:
setNames(input_vector, assigned_names)
where,
1. input_vector is the vector
2. assigned_names are the names to the elements of input vector.
Example:
In this example, we are going to create a vector with 10 elements and assign the letters as names with setNames() method.
# create vector and assign names input_vector = setNames ( c (1: 10), letters [1:10])
# display print (input_vector)
|
Output:
a b c d e f g h i j 1 2 3 4 5 6 7 8 9 10
setnames:
setnames are available in data.table package used to name the columns in a data frame.
Syntax:
setNames(input_dataframe, c(old_column_name1,…..,old_column_name n),c(new_column_name1,…..,new_column_name n))
where,
1. input_dataframe is the dataframe
2. old_column_name is the old name and new_column_name is the new name
Example:
In this example, we are going to create a dataframe with 3 elements and rename the column names using setnames() method. We specified columns as v1,v2 and v3, now we will rename them to col1, col2, and col3.
# load the data.table module library ( "data.table" )
# create dataframe data = data.frame (v1=1: 5, v2=6: 10, v3=11: 15)
# display print (data)
# change all column names of # the dataframe. setnames (data, c ( "v1" , "v2" , "v3" ),
c ( "col1" , "col2" , "col3" ))
# display data |
Output:
The differences that we observed is
v1 v2 v3 1 1 6 11 2 2 7 12 3 3 8 13 4 4 9 14 5 5 10 15 col1 col2 col3 1 1 6 11 2 2 7 12 3 3 8 13 4 4 9 14 5 5 10 15
setnames() is available in data.table() package and setNames() is available in stats package.