R unlist() Function - Flattening a List into a Vector
The R unlist() function is used to flatten a list into a vector.
When all elements in a list have the same type, unlist() can convert it to a vector for uniform processing.
The syntax of the unlist() function is as follows:
unlist(x, recursive = TRUE, use.names = TRUE)
Parameter Description:
-
x An input list.
-
use.names Whether to keep element names, defaults to TRUE.
Example
Create from a numeric list
num_list
<-
list
(
group1
=
c
(
1
,
2
,
3
)
,
group2
=
c
(
4
,
5
,
6
)
,
group3
=
c
(
7
,
8
,
9
)
)
Flatten into a vector
flat
<-
unlist
(
num_list
)
(
"Flattened vector:"
)
(
flat
)
Can be used for direct calculation
(
paste
(
"Sum:"
,
sum
(
flat
)
)
)
(
paste
(
"Mean:"
,
mean
(
flat
)
)
)
Flattening a mixed-type list converts it to characters
mixed_list
<-
list
(
a
=
1
, b
=
"hello"
,
c
=
3
)
flat_mixed
<-
unlist
(
mixed_list
)
(
"Mixed-type flattening:"
)
(
flat_mixed
)
The output of the code above is:
[1] "展平后的向量:"
group11 group12 group13 group21 group22 group23 group31 group32 group33
1 2 3 4 5 6 7 8 9
[1] "总和: 45"
[1] "均值: 5"
[1] "混合类型展平:"
a b c
"1" "hello" "3"
R Language Examples