r - 将 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 是最后一个数字。
有人有想法吗?
解决方案
一个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
推荐阅读
- javascript - 画布上下文过滤器模糊在 ios safari/chrome 中不起作用
- javascript - 最后选择的文件的内存存储在哪里,如何清除它?
- xml - Google Blogger 模板 - XML 文件重定向 URL
- linux - 如何从 bash (Linux) 打开应用程序
- python - Pandas:获取具有唯一值和多列最高分的字典
- r - 是否可以为 do.call 提供未使用的参数?
- c++ - 将子对象存储在父对象中
- vue.js - 数组输出在 vue 中使用 EMAILJS 库不起作用
- javascript - MongoDB 寻找最匹配的用户
- swift - Sentry:事件在堆栈跟踪中缺少数字行