Write a R program to store data into a List and perform different operations

1. Introduction

This R program demonstrates how to store data in a list and then perform various operations on it. Lists in R are versatile structures that can hold a variety of data types and structures.

2. Program Steps

1. Create a list with various types of data.

2. Access a specific element in the list.

3. Modify an element in the list.

4. Append a new element to the list.

5. Remove an element from the list.

6. Print the final list after all operations.

3. Code Program

# Step 1: Create a list with various data
data_list <- list(number = 42, name = "John Doe", scores = c(80, 90, 100))

# Step 2: Access a specific element (name)
accessed_name <- data_list$name

# Step 3: Modify an element (number)
data_list$number <- 100

# Step 4: Append a new element (new item)
data_list$isNew <- TRUE

# Step 5: Remove an element (scores)
data_list$scores <- NULL

# Step 6: Print the final list
print("Final List after operations:")
print(data_list)

Output:

Final List after operations:
$number
[1] 100
$name
[1] "John Doe"
$isNew
[1] TRUE

Explanation:

1. list(number = 42, name = "John Doe", scores = c(80, 90, 100)): Creates a list containing a number, a name, and a vector of scores.

2. data_list$name: Accesses the 'name' element in the list.

3. data_list$number <- 100: Modifies the 'number' element of the list to 100.

4. data_list$isNew <- TRUE: Appends a new boolean element 'isNew' to the list.

5. data_list$scores <- NULL: Removes the 'scores' element from the list.

6. print("Final List after operations:"), print(data_list): Prints the final list after performing all the operations.


Comments