我有一个以制表符分隔的数据文件,其中有四列,我希望读取R中的前两列,并且只保留唯一的两列对作为data.frame
。文件可以在数百万行中:
cluster-1 3 12412341324 13412341234
cluster-1 3 62626662346 54234524354
cluster-1 3 45454345354 45454544545
cluster-2 644 12332234341 37535473475
cluster-2 644 54654365466 56565634543
cluster-2 644 56356356536 35634563456
...
cluster-9999999 123 123412341241 143132423
...
我想使用scan
(或任何更好的选择)来读取该文件,并最终得到一个具有以下内容的data.frame
:
cluster-1 3
cluster-2 644
cluster-3 343
...
cluster-9999999 123
在R中读取这么大的文件最省时的方法是什么?
发布于 2013-02-11 17:56:26
:如果您知道列数,比如说5列,并且您想要前两列(或者只有几列),那么可以使用read.table
中的colClasses
来完成这项工作
# header here is set to false because I don't see one in your file
df <- read.table("~/file.txt", header = FALSE,
colClasses=c("character", "numeric", "NULL", "NULL", "NULL"))
在这里,我们将第3到5列设置为NULL
,以便跳过它们。
未知列/大量列:如果您不知道列或列太多,另一种方法是使用带有awk
的pipe
(或带有cut
的pipe
),首先使用所需的列过滤文件,然后使用read.table
加载文件
# header here is set to false because I don't see one in your file
df <- read.table(pipe("awk '{print $1\"\t\"$2}' ~/file.txt"),
header = FALSE, sep = "\t")
删除重复的行:使用duplicated
from base
作为:
df <- df[!duplicated(df), ]
https://stackoverflow.com/questions/14809407
复制相似问题