R unlist() Function - Flatten Lists into Vectors

R 语言实例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 into a vector for unified processing.

The syntax of the unlist() function is as follows:

unlist(x, recursive = TRUE, use.names = TRUE)

Parameter description:

  • xThe input list.

  • use.namesWhether to preserve element names, defaults to TRUE.

Example

# Created 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 character
mixed_list <- list(a = 1, b = "hello", c = 3)
flat_mixed <- unlist(mixed_list)
print("Mixed-type flattened:")
print(flat_mixed)

Executing the above code produces the following output:

[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 语言实例R Language Examples

Other Extensions