📌  相关文章
📜  在 R 编程中将对象转换为列表 - as.list()函数

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

在 R 编程中将对象转换为列表 - as.list()函数

R 编程语言中的as.list()函数用于将对象转换为列表。这些对象可以是向量、矩阵、因子和数据框。

R – as.list()函数示例

示例 1:在 R 语言中使用 as.list()函数将向量转换为列表

R
# R program to convert object to list
 
# Creating vector
x < - c(1, 2, 3, 4, 5)
 
# Calling as.list() Function
as.list(x)


R
# R program to convert object to list
 
# Calling pre-defined data set
BOD
 
# Calling as.list() Function
as.list(BOD)


R
# R program to create a matrix
# and then convert into list
 
A = matrix(
     
# Taking sequence of elements
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
 
# No of rows
nrow = 3,
 
# No of columns
ncol = 3,       
 
# By default matrices are in column-wise order
# So this parameter decides how to arrange the matrix
byrow = TRUE       
)
 
# Naming rows
rownames(A) = c("a", "b", "c")
 
# Naming columns
colnames(A) = c("c", "d", "e")
 
cat("The 3x3 matrix:\n")
print(A)
 
 
lst = as.list(A)
lst


输出:

[[1]]
[1] 1

[[2]]
[1] 2

[[3]]
[1] 3

[[4]]
[1] 4

[[5]]
[1] 5

示例 2:在 R 语言中使用 as.list()函数将数据框转换为列表

R

# R program to convert object to list
 
# Calling pre-defined data set
BOD
 
# Calling as.list() Function
as.list(BOD)

输出:

Time demand
1    1    8.3
2    2   10.3
3    3   19.0
4    4   16.0
5    5   15.6
6    7   19.8
$Time
[1] 1 2 3 4 5 7

$demand
[1]  8.3 10.3 19.0 16.0 15.6 19.8

attr(, "reference")
[1] "A1.4, p. 270"

示例 3:在 R 语言中使用 as.list()函数将矩阵转换为列表

R

# R program to create a matrix
# and then convert into list
 
A = matrix(
     
# Taking sequence of elements
c(1, 2, 3, 4, 5, 6, 7, 8, 9),
 
# No of rows
nrow = 3,
 
# No of columns
ncol = 3,       
 
# By default matrices are in column-wise order
# So this parameter decides how to arrange the matrix
byrow = TRUE       
)
 
# Naming rows
rownames(A) = c("a", "b", "c")
 
# Naming columns
colnames(A) = c("c", "d", "e")
 
cat("The 3x3 matrix:\n")
print(A)
 
 
lst = as.list(A)
lst

输出:

The 3x3 matrix:
  c d e
a 1 2 3
b 4 5 6
c 7 8 9
[[1]]
[1] 1

[[2]]
[1] 4

[[3]]
[1] 7

[[4]]
[1] 2

[[5]]
[1] 5

[[6]]
[1] 8

[[7]]
[1] 3

[[8]]
[1] 6

[[9]]
[1] 9