YouTip LogoYouTip

R Func Unlist

# R unlist() Function - Flatten List to Vector [![Image 3: R Language Examples](#) R Language Examples](#) The R unlist() function is used to flatten a list into a vector. When all elements in the list are of 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:** * **x** Input list. * **use.names** Whether to retain 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 to 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 to Character mixed_list <-list(a =1, b ="hello", c=3) flat_mixed <-unlist(mixed_list) print("Flattening Mixed Types:") print(flat_mixed) Executing the above code outputs the following result: "Flattened Vector:" group11 group12 group13 group21 group22 group23 group31 group32 group33 1 2 3 4 5 6 7 8 9 "Sum: 45" "Mean: 5" "Flattening Mixed Types:" a b c "1" "hello" "3" [![Image 4: R Language Examples](#) R Language Examples](#)
← R Func WhichR Func Trimws β†’