我有一个包含四列的制表符分隔数据文件,我想在 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 中读取这个大文件的最省时的方法是什么?
最佳答案
已知且相对较少的列:如果您知道列数,例如 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
,以便跳过它们。
Unknown columns/Lot of columns:如果您不知道列或列太多,另一种选择是使用 pipe
和 awk
(或 pipe
with cut
)首先用你需要的列过滤文件,然后使用 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")
删除重复行:使用 base
中的 duplicated
作为:
df <- df[!duplicated(df), ]
关于R扫描两列并保持唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14809407/