R names() Function - Name Operations
The R names() function is used to get or set the names attribute of an object.
names() can be applied to vectors, lists, and data frames to manage the names of elements.
The syntax of the names() function is as follows:
names(x)
names(x) <- value
Parameter Description:
-
x Input object (vector, list, or data frame).
-
value A vector of names to set.
Example
Set names for vector elements
scores
<-
c
(
88
,
92
,
76
,
85
,
90
)
names
(
scores
)
<-
c
(
"Zhang San"
,
"Li Si"
,
"Wang Wu"
,
"Zhao Liu"
,
"Qian Qi"
)
(
"Named vector:"
)
(
scores
)
Access elements by name
(
paste
(
"Li Si's score:"
, scores
[
"Li Si"
]
)
)
Get and modify data frame column names
df
<-
data.frame
(
a
=
1
:
3
, b
=
4
:
6
)
(
"Column names before modification:"
)
(
names
(
df
)
)
names
(
df
)
<-
c
(
"Column One"
,
"Column Two"
)
(
"Column names after modification:"
)
(
names
(
df
)
)
The output of the code above is:
[1] "带名称的向量:"
张三 李四 王五 赵六 钱七
88 92 76 85 90
[1] "李四的成绩: 92"
[1] "修改前列名:"
[1] "a" "b"
[1] "修改后列名:"
[1] "列一" "列二"
R Language Examples