Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R unlist() Function - Flattening a List into a Vector

R unlist() Function - Flattening a List into a Vector

R Language Examples R Language Examples

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:

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

)

print

(

"Flattened vector:"

)

print

(

flat

)

Can be used for direct calculation

print

(

paste

(

"Sum:"

,

sum

(

flat

)

)

)

print

(

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

)

print

(

"Mixed-type flattening:"

)

print

(

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 R Language Examples