开始使用免费开始使用

使用 col_types 与 collectors

设置导入列类型的另一种方式是使用收集器(collector)。可以将收集器函数放入 list(),并传递给 read_ 系列函数的 col_types 参数,用来告知应如何解析某一列中的值。

如需完整的收集器函数列表,请查看 collector 文档。本练习中您将用到两个收集器函数:

  • col_integer():该列应按整数解析。
  • col_factor(levels, ordered = FALSE):该列应按具有给定 levels 的因子解析。

在本练习中,您将使用 hotdogs.txt查看),这是一个以制表符分隔、且首行不含列名的文件。

本练习是课程的一部分

R 数据导入入门

查看课程

练习说明

  • 已为您创建了未设置列类型的 hotdogs。使用 summary() 函数查看其汇总信息。
  • 已为您定义了两个收集器函数:facint。看一看它们,您是否理解它们分别收集什么类型?
  • 在第二个 read_tsv() 调用中,编辑 col_types 参数:传入包含 facintintlist(),使第一列导入为因子,第二、第三列导入为整数。
  • hotdogs_factor 调用 summary()。将其与 hotdogs 的汇总信息进行比较。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import without col_types
hotdogs <- read_tsv("hotdogs.txt", col_names = c("type", "calories", "sodium"))

# Display the summary of hotdogs
___

# The collectors you will need to import the data
fac <- col_factor(levels = c("Beef", "Meat", "Poultry"))
int <- col_integer()

# Edit the col_types argument to import the data correctly: hotdogs_factor
hotdogs_factor <- read_tsv("hotdogs.txt",
                           col_names = c("type", "calories", "sodium"),
                           col_types = NULL)

# Display the summary of hotdogs_factor
___
编辑并运行代码