首页 > 解决方案 > 将 file.txt 加载到 R 中的 df

问题描述

我需要帮助才能将文件内容转换为数据框。

这是文件:

>OK0100087.1
0 375
376 750
751 1000
>OK0100088.1
0 87766
>OK0100089.1
0 66778
>OK0100090.1
0 47519
47520 73733

我的想法是我想在 df 中更改此文件内容,例如:

Name           start end
OK0100087.1_0  0      375
OK0100087.1_1  376    750
OK0100087.1_2  751    1000
OK0100088.1    0      87766
OK0100089.1    0      66778
OK0100090.1_0  0      47519
OK0100090.1_1  47520  73733

如果在>OK...number

其中 start 是每行的第一个数字, end 是最后一个数字。

有人有想法吗?

标签: rdataframe

解决方案


一个base解决方案:

txt <- readLines("foo.txt")
grp <- cumsum(grepl("^>", txt))
Reduce(rbind, by(txt, grp, function(x){
  name <- sub("^>", "", x[1])
  cbind(Name = if(length(x) > 2) paste(name, seq_along(x[-1])-1, sep = "_") else name,
        read.table(text = x[-1], col.names = c("start", "end")))
}))

#            Name start   end
# 1 OK0100087.1_0     0   375
# 2 OK0100087.1_1   376   750
# 3 OK0100087.1_2   751  1000
# 4   OK0100088.1     0 87766
# 5   OK0100089.1     0 66778
# 6 OK0100090.1_0     0 47519
# 7 OK0100090.1_1 47520 73733

推荐阅读