Write R code to create a list called car with elements: make = "Toyota", year = 2020, and features = c("Airbags", "GPS", "Bluetooth"). Then update the year to 2021 and add a new element color = "Red".
Lists are flexible data structures that can store elements of different types, including numbers, characters, vectors, and even other lists.
Use the list()
function:
person <- list(
name = "Alice",
age = 25,
scores = c(90, 85, 88)
)
Use $
for named elements or [[ ]]
for indexing:
person$name # "Alice"
person[["age"]] # 25
person$scores # c(90, 85, 88)
You can add or update elements easily:
person$city <- "London"
person$age <- 26
Lists are useful for storing structured or heterogeneous data.