我有由大约94列和300万行组成的大数据集。此文件在列之间使用单个和多个空格作为分隔符。我需要从R中的这个文件中读取一些列。为此,我尝试使用带有选项的read.table(),这些选项可以在下面的代码中看到,代码粘贴在下面-
### 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)由于必须读入的文件在某些列之间有多个空格作为分隔符,因此上述方法不起作用。有没有什么方法可以让我们有效地读入这个文件。
发布于 2013-06-07 16:51:36
您需要更改您的分隔符。" "指的是一个空白字符。""引用任何长度的空格作为分隔符
data <- read.table(file, sep = "" , header = F , nrows = 100,
na.strings ="", stringsAsFactors= F)从手册中:
If sep = "“(read.table的默认值)分隔符是‘空白’,即一个或多个空格、制表符、换行符或回车符。
此外,对于大型数据文件,您可能需要考虑使用data.table:::fread将数据直接快速读取到data.table中。今天早上我自己也在使用这个函数。它仍然是试验性的,但我发现它确实工作得很好。
发布于 2018-08-28 15:16:23
如果您希望使用tidyverse (或分别使用readr )包,则可以使用read_table。
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 = "")在描述中可以看到:
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.发布于 2015-11-30 23:16:40
如果你的字段有一个固定的宽度,你应该考虑使用read.fwf(),它可以更好地处理缺失值。
https://stackoverflow.com/questions/16979858
复制相似问题