📜  在 R 编程中获取或设置对象元素的名称 - names()函数

📅  最后修改于: 2022-05-13 01:55:35.225000             🧑  作者: Mango

在 R 编程中获取或设置对象元素的名称 - names()函数

R 语言中的names()函数用于获取或设置对象的名称。此函数将对象(即向量、矩阵或数据框)作为参数以及将作为名称分配给对象的值。传递的值向量的长度必须完全等于要命名的对象的长度。

示例 1:

# R program to assign name to an object
  
# Creating a vector
x <- c(1, 2, 3, 4, 5)
  
# Assigning names using names() function
names(x) <- c("gfg1", "gfg2", "gfg3", "gfg4", "gfg5")
  
# Printing name vector that is assigned 
names(x)
  
# Printing updated vector
print(x)

输出:

[1] "gfg1" "gfg2" "gfg3" "gfg4" "gfg5"
gfg1 gfg2 gfg3 gfg4 gfg5 
   1    2    3    4    5 

示例 2:

# R program to get names of an Object
  
# Importing Library 
library(datasets) 
    
# Importing dataset 
head(airquality) 
  
# Calling names() function to get names
names(airquality)

输出:

Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6
[1] "Ozone"   "Solar.R" "Wind"    "Temp"    "Month"   "Day"