使用 col_types 与 collectors
设置导入列类型的另一种方式是使用收集器(collector)。可以将收集器函数放入 list(),并传递给 read_ 系列函数的 col_types 参数,用来告知应如何解析某一列中的值。
如需完整的收集器函数列表,请查看 collector 文档。本练习中您将用到两个收集器函数:
col_integer():该列应按整数解析。col_factor(levels, ordered = FALSE):该列应按具有给定levels的因子解析。
在本练习中,您将使用 hotdogs.txt(查看),这是一个以制表符分隔、且首行不含列名的文件。
本练习是课程的一部分
R 数据导入入门
练习说明
- 已为您创建了未设置列类型的
hotdogs。使用summary()函数查看其汇总信息。 - 已为您定义了两个收集器函数:
fac和int。看一看它们,您是否理解它们分别收集什么类型? - 在第二个
read_tsv()调用中,编辑col_types参数:传入包含fac、int和int的list(),使第一列导入为因子,第二、第三列导入为整数。 - 对
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
___