R Program to Convert a List to a Vector

1. Introduction

Lists are one of the most versatile data structures in R. They can hold elements of different types and can even contain other lists. However, sometimes you might need to simplify a list into a vector. In this guide, we will show you how to convert a list into a vector in R.

2. Program Steps

1. Create a sample list.

2. Convert the list to a vector using the unlist function.

3. Code Program

# Create a sample list
sample_list <- list(a = 1:5, b = 6:10, c = 11:15)

# Display the original list
print("Original List:")
print(sample_list)

# Convert the list to a vector
vector_result <- unlist(sample_list)

# Display the resultant vector
print("Converted Vector:")
print(vector_result)

Output:

[1] "Original List:"
$a
[1] 1 2 3 4 5

$b
[1] 6 7 8 9 10

$c
[1]  11 12 13 14 15

[1] "Converted Vector:"
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

4. Step By Step Explanation

- We begin by creating a sample list named sample_list. This list has three components: a, b, and c, each holding a sequence of five integers.

- To convert the list into a vector, we use the unlist function. This function takes a list as an input and returns a single vector combining all the components of the list.

- As observed in the output, the result is a single vector that contains all the elements from the list's components concatenated in order.

Comments