开始使用免费开始使用

列的类型

参数 colClasses 允许您为读取的文件中每一列指定数据类型。这既能提升导入效率,也能确保各列以正确的数据类型读入。

您可以通过设置 colClasses 参数来完成:

read.delim("my_file.txt", 
           colClasses = c("character",
                          "numeric",
                          "logical"))

如果在 colClasses 向量中将某一列设为 "NULL",则会跳过该列,不会将其加载进数据框。

本练习是课程的一部分

R 数据导入入门

查看课程

练习说明

  • hotdogs 数据框已加载。请先显示 hotdogs 的结构。
  • 在第二个 read.delim() 调用的 colClasses 参数中,将第 1、2、3 列分别设置为 'character''NULL''numeric'
  • 显示 hotdogs2 的结构,并比较它们的差异。

交互式实操练习

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

# Previous call to import hotdogs.txt
hotdogs <- read.delim("hotdogs.txt", header = FALSE, col.names = c("type", "calories", "sodium"))

# Display structure of hotdogs
___

# Edit the colClasses argument to import the data correctly: hotdogs2
hotdogs2 <- read.delim("hotdogs.txt", header = FALSE, 
                       col.names = c("type", "calories", "sodium"),
                       colClasses = c(___, ___, ___))


# Display structure of hotdogs2
___
编辑并运行代码