Adding and Deleting List Elements
In R, you can add and delete elements from a list dynamically.
Adding Elements to List:
There are different ways to add elements to the list, those are,
- Using $ Operator (for Named Elements):
By using this operator, you can add elements to the named list.
Example:
> users <- list(name = "Naveen", age = 32)
> # adding an element to list
> users$city <- "Hyd"
> print(users)
$name
[1] "Naveen"
$age
[1] 32
$city
[1] "Hyd"
- Using [[ ]] (for Named or Indexed Elements):
By using this operator, you can add elements to the named list or indexed list.
Example:
> users[["country"]] <- "India"
> print(users)
$name
[1] "Naveen"
$age
[1] 32
$city
[1] "Hyd"
$country
[1] "India"
- Using c() Function (for Appending Elements):
By using c() function, you can append elements to list.
Example:
> users <- c(users, list(gender = "Male"))
> print(users)
$name
[1] "Naveen"
$age
[1] 32
$city
[1] "Hyd"
$country
[1] "India"
$gender
[1] "Male"
Deleting Elements from List:
There are different ways to delete elements from the list, those are,
- Assign NULL to Remove an Element:
You can remove element from the list by assigning NULL value to it.
Example:
> users$city <- NULL
> print(users)
$name
[1] "Naveen"
$age
[1] 32
$country
[1] "India"
$gender
[1] "Male"
> users[["country"]] <- NULL
> print(users)
$name
[1] "Naveen"
$age
[1] 32
$gender
[1] "Male"
- Using [-index] or Negative Indexing:
Example:
> users <- users[-2] # removing 2nd element (age)
> print(users)
$name
[1] "Naveen"
$gender
[1] "Male"