title: R_4 列表date: 2021-07-11
tags: R语言
categories: 学习
mathjax: true

4. 列表

列表也是一维元素的集合。与向量的不同之处在于:
(1)可以存储不同类型的元素;
(2)可以用名称进行标记、用标记的名称来引用元素。向量也可以用名称标记元素,但是我们不这样做。
同样的数据结构在Python中被称为字典,列表对组织数据非常有用。

4.1 创建列表

使用list()函数创建列表,最好为每一个元素指定名称。

  1. person1 <- list( #这是小括号而不是大括号
  2. first_name = "Ada", #使用等于号而不是箭头,用逗号分隔
  3. job = "Programmer",
  4. salary = 78000,
  5. in_union = TRUE
  6. )
  7. #也可以不写名称
  8. person2 <- list("Amy","salesperson",67000,FALSE)

使用names()访问列表中的名称。

names(person1)

列表的元素也可以是列表。

person3 <- list(
    first_name = "Adam",  
    job = "Programmer",
    salary = 78000,
    in_union = TRUE,
    favorites = list(
      music = "pop",
      food = "pasta"
    )
)

4.2 访问列表元素

使用美元符号访问列表中的元素。

print(person1)
print(person2$first_name)

也可以使用双方括号和索引或名称访问列表中的元素。

print(person2[[2]])
print(person3[["first_name"]])

4.3 修改列表

先访问列表元素,再对其赋值即可修改。若赋值NULL,则代表“未定义”。NA代表缺少的值,是一个洞;NULL代表未定义,不是一个洞

4.3.1 单括号和双括号

单括号意为“过滤”,在向量中使用单括号实际上是按括号中的索引进行过滤。对列表里来说,单括号返回的是一个列表,而双括号返回列表中的元素。

4.4 使用函数

向量可以直接作为函数的参数,但是列表需要使用lapply()函数。该函数有两个参数,第一个是要作用的列表,另一个是应用于每一项的函数。

lapply(list("a","b"), paste,"dances.")

sapply()函数作用于向量且只针对自定义函数

4.5 本章练习

Exercise 1

# Exercise 1: creating and accessing lists

# Create a vector `my_breakfast` of everything you ate for breakfast

my_breakfast <- c("cake","apple","milk")

# Create a vector `my_lunch` of everything you ate (or will eat) for lunch

my_lunch <- c("rice","noodle","meat")

# Create a list `meals` that has contains your breakfast and lunch

meals <- list(
  breakfast = my_breakfast,
  lunch = my_lunch
  )

# Add a "dinner" element to your `meals` list that has what you plan to eat 
# for dinner

meals$dinner <- c("rice","vegetables","meat")

# Use dollar notation to extract your `dinner` element from your list
# and save it in a vector called 'dinner'

dinner <- meals$dinner

# Use double-bracket notation to extract your `lunch` element from your list
# and save it in your list as the element at index 5 (no reason beyond practice)

meals[[5]] <- meals[["lunch"]]

# Use single-bracket notation to extract your breakfast and lunch from your list
# and save them to a list called `early_meals`

early_meals <- meals[c("breakfast","lunch")]

### Challenge ###

# Create a list that has the number of items you ate for each meal
# Hint: use the `lapply()` function to apply the `length()` function to each item

item_number <- lapply(meals,length)

# Write a function `add_pizza` that adds pizza to a given meal vector, and
# returns the pizza-fied vector

add_pizza <- function(meal)
{
  meal[length(meal) + 1] <- "pizza"
  return(meal)
}

# Create a vector `better_meals` that is all your meals, but with pizza!

better_meals <- add_pizza(meals[["dinner"]])