R编程中的命名列表
列表是 R 语言中由异构元素组成的对象。列表甚至可以包含矩阵、数据框或函数作为其元素。可以使用 R 中的list()函数创建列表。命名列表也可以通过指定访问它们的元素的名称使用相同的函数创建。也可以使用names()函数创建命名列表,以在定义列表后指定元素的名称。在本文中,我们将学习在 R 中使用两种不同的方法和可以对命名列表执行的不同操作来创建命名列表。
Syntax: names(x) <- value
Parameters:
x: represents an R object
value: represents names that has to be given to elements of x object
创建命名列表
可以通过两种方法创建命名列表。第一种方法是在定义列表时为元素分配名称,另一种方法是使用names()函数。
示例 1:
在此示例中,我们将不使用names()函数创建一个命名列表。
# Defining a list with names
x <- list(mt = matrix(1:6, nrow = 2),
lt = letters[1:8],
n = c(1:10))
# Print whole list
cat("Whole List:\n")
print(x)
输出:
Whole List:
$mt
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
$lt
[1] "a" "b" "c" "d" "e" "f" "g" "h"
$n
[1] 1 2 3 4 5 6 7 8 9 10
示例 2:
在此示例中,我们将在定义列表后使用names()函数定义列表元素的名称。
# Defining list
x <- list(matrix(1:6, nrow = 2),
letters[1:8],
c(1:10))
# Print whole list
cat("Whole list:\n")
print(x)
输出:
Whole list:
[[1]]
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
[[2]]
[1] "a" "b" "c" "d" "e" "f" "g" "h"
[[3]]
[1] 1 2 3 4 5 6 7 8 9 10
访问命名列表的组件
$ 运算符可以轻松访问命名列表的组件。
例子:
# Defining a list with names
x <- list(mt = matrix(1:6, nrow = 2),
lt = letters[1:8],
n = c(1:10))
# Print list elements using the names given
# Prints element of the list named "mt"
cat("Element named 'mt':\n")
print(x$mt)
cat("\n")
# Print element of the list named "n"
cat("Element named 'n':\n")
print(x$n)
输出:
Element named 'mt':
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
Element named 'n':
[1] 1 2 3 4 5 6 7 8 9 10
修改命名列表的组件
可以通过为它们分配新值来修改命名列表的组件。
例子:
# Defining a named list
lt <- list(a = 1,
let = letters[1:8],
mt = matrix(1:6, nrow = 2))
cat("List before modifying:\n")
print(lt)
# Modifying element named 'a'
lt$a <- 5
cat("List after modifying:\n")
print(lt)
输出:
List before modifying:
$a
[1] 1
$let
[1] "a" "b" "c" "d" "e" "f" "g" "h"
$mt
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
List after modifying:
$a
[1] 5
$let
[1] "a" "b" "c" "d" "e" "f" "g" "h"
$mt
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
从命名列表中删除组件
要从命名列表中删除元素,我们将使用within()函数,结果将分配给命名列表本身。
例子:
# Defining a named list
lt <- list(a = 1,
let = letters[1:8],
mt = matrix(1:6, nrow = 2))
cat("List before deleting:\n")
print(lt)
# Modifying element named 'a'
lt <- within(lt, rm(a))
cat("List after deleting:\n")
print(lt)
输出:
List before deleting:
$a
[1] 1
$let
[1] "a" "b" "c" "d" "e" "f" "g" "h"
$mt
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
List after deleting:
$let
[1] "a" "b" "c" "d" "e" "f" "g" "h"
$mt
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6