首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >读取R中以多个空格为分隔符的文本文件

读取R中以多个空格为分隔符的文本文件
EN

Stack Overflow用户
提问于 2013-06-07 16:46:02
回答 3查看 96.5K关注 0票数 72

我有由大约94列和300万行组成的大数据集。此文件在列之间使用单个和多个空格作为分隔符。我需要从R中的这个文件中读取一些列。为此,我尝试使用带有选项的read.table(),这些选项可以在下面的代码中看到,代码粘贴在下面-

代码语言:javascript
复制
### Defining the columns to be read from the file, the first 5 column, then we do not read next 24, after this we read next 5 columns. Last 60 columns are not read in-

    col_classes = c(rep("character",2), rep("numeric", 3), rep("NULL",24), rep("numeric", 5), rep("NULL", 60))   

### Reading first 100 rows of the data

    data <- read.table(file, sep = " ",header = F, nrows = 100, na.strings ="", stringsAsFactors= F)

由于必须读入的文件在某些列之间有多个空格作为分隔符,因此上述方法不起作用。有没有什么方法可以让我们有效地读入这个文件。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-06-07 16:51:36

您需要更改您的分隔符。" "指的是一个空白字符。""引用任何长度的空格作为分隔符

代码语言:javascript
复制
 data <- read.table(file, sep = "" , header = F , nrows = 100,
                     na.strings ="", stringsAsFactors= F)

从手册中:

If sep = "“(read.table的默认值)分隔符是‘空白’,即一个或多个空格、制表符、换行符或回车符。

此外,对于大型数据文件,您可能需要考虑使用data.table:::fread将数据直接快速读取到data.table中。今天早上我自己也在使用这个函数。它仍然是试验性的,但我发现它确实工作得很好。

票数 104
EN

Stack Overflow用户

发布于 2018-08-28 15:16:23

如果您希望使用tidyverse (或分别使用readr )包,则可以使用read_table

代码语言:javascript
复制
read_table(file, col_names = TRUE, col_types = NULL,
  locale = default_locale(), na = "NA", skip = 0, n_max = Inf,
  guess_max = min(n_max, 1000), progress = show_progress(), comment = "")

在描述中可以看到:

代码语言:javascript
复制
read_table() and read_table2() are designed to read the type of textual data where
each column is #' separate by one (or more) columns of space.
票数 7
EN

Stack Overflow用户

发布于 2015-11-30 23:16:40

如果你的字段有一个固定的宽度,你应该考虑使用read.fwf(),它可以更好地处理缺失值。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16979858

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档