【发布时间】:2013-06-03 12:14:44
【问题描述】:
我有大约 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)
由于必须读入的文件在某些列之间有多个空格作为分隔符,因此上述方法不起作用。有没有什么方法可以有效地读取这个文件。
【问题讨论】:
-
只需删除
sep=" "参数。read.table默认知道如何处理多个空格。 -
我有一个非常相似的问题,但我需要一个更通用的解决方案,因为我在某些字段中有单个空格。这意味着我应该能够将最小连续空格数(在我的情况下为 2)设置为分隔符,没有限制。
-
@HongOoi: 是的,但只是因为
read.table/read.csv的默认值是 sep="",这意味着“多个空格”,我们可能期望它应该是一个正则表达式“\w*”或“\ w+" 不是 ""。