Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R names() Function - Name Operations

R names() Function - Name Operations

R Language Examples R Language Examples

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:

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"

)

print

(

"Named vector:"

)

print

(

scores

)

Access elements by name

print

(

paste

(

"Li Si's score:"

, scores

[

"Li Si"

]

)

)

Get and modify data frame column names

df

<-

data.frame

(

a

=

1

:

3

, b

=

4

:

6

)

print

(

"Column names before modification:"

)

print

(

names

(

df

)

)

names

(

df

)

<-

c

(

"Column One"

,

"Column Two"

)

print

(

"Column names after modification:"

)

print

(

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 R Language Examples