2015-05-19 57 views
1

我的文本文件“myfile.txt”包含许多具有相同列(名称,年龄,体重,职业)的表格。它看起来像:如何将一个文本文件中的多个表格转换为一个具有附加列的表格?

table_ID 001 
John | 38 | 165 | Computer scientist 
Mary | 22 | 122 | Student 

table_ID 002 
Patric| 44 | 105 | Teacher 
Kim | 56 | 155 | Salesman 
Kate | 33 | 133 | Student 
... 

table_ID 100 
Peter| 44 | 105 | Teacher 
Han | 56 | 155 | Salesman 
Ken | 33 | 133 | Student 

I want to output a data.frame with an additional column ("table_ID"), which looks like: 

table_ID name age weight profession 
001 John 38 165 Computer scientist 
001 Mary 22 122 Student 
002 Patric 44 105 Teacher 
002 Kim 56 155 Salesman 
002 Kate 33 133 Student 
... 

100 Peter 44 105 Teacher 
100 Han 56 155 Salesman 
100 Ken 33 133 Student 

如何在R中执行此操作?非常感谢。

+0

你有这个'|'在'myfile.txt的” – akrun

+0

Akrun,感谢您的魔术!其实我的table_ID并不像上面显示的那么简单,它们有点不规则:NM_000775,NM_001014975,NM_001080484等等。常见的是前面的字符串“table_ID”。你如何处理这种情况? –

+0

更新了解决方案。我复制/粘贴输入数据并保存为文件。它似乎为我工作。希望它适用于您的原始数据 – akrun

回答

1

您可以尝试

library(tidyr) 
lines <- readLines('paul.txt') 
indx <- grepl('table_ID', lines) 
lst <- split(lines, cumsum(indx)) 
names(lst) <- sub('\\D+', '', sapply(lst,`[`, 1)) 
res <- unnest(lapply(lst, function(x) 
    read.table(text=x[-1], header=FALSE, sep="|")), table_ID) 
相关问题