在 R 语言中将列表转换为向量 - unlist()函数
R 语言中的unlist()
函数用于将列表转换为向量。它通过保留所有组件来简化生成向量的过程。
Syntax: unlist(list)
Parameters:
list: It is a list or Vector
use.name: Boolean value to prserve or not the position names
示例 1:将列表数值向量转换为单个向量
# R program to illustrate
# converting list to vector
# Creating a list.
my_list <- list(l1 = c(1, 3, 5, 7),
l2 = c(1, 2, 3),
l3 = c(1, 1, 10, 5, 8, 65, 90))
# Apply unlist R function
print(unlist(my_list))
输出:
l11 l12 l13 l14 l21 l22 l23 l31 l32 l33 l34 l35 l36 l37
1 3 5 7 1 2 3 1 1 10 5 8 65 90
在上面的代码中,我们使用unlist()
列出 my_list 并将其转换为单个向量。
如上图所示,列表将解散,每个元素都将位于如上所示的同一行中。
示例 2:使用数据框取消列出列表:
# R program to illustrate
# Unlisting list with data frame
# Creating a list.
my_list <- list(l1 = c(1, 3, 5, 7),
l2 = c(1, 2, 3),
l3 = c(1, 1, 10, 5, 8, 65, 90))
# Create modified list
my_list_2 <- my_list
# Add a data frame to the list
my_list_2[[4]] <- data.frame(x1 = c(1, 2, 3),
x2 = c(4, 5, 6))
# Unlist list with data.frame
print(unlist(my_list_2, use.names = FALSE))
输出:
[1] 1 3 5 7 1 2 3 1 1 10 5 8 65 90 1 2 3 4 5 6
在上面的代码中,我们修改了之前的列表,并在“my_list_2”中添加了新元素,并在其上使用了函数unlist()
。
此外,我们将“use.name”参数设置为“FALSE”,因此我们不会看到向量中值的位置名称。