2014-04-01 48 views
-1

我有一个文本文件中的数据集,它只有2列但数据中有多个分节符,我想将其放入单独的数组中,其中数组的名称是在“Ran:”旁边的第二列中的文本。下面是一个样本数据集:R:如何根据部分分开外部文本数据

ABCDEFG 
Authored by test 
Ran: Efg$ 
Test: num85 
1  50 
2  52 
3  54 
Ran: pg2 
Test: num85 
1  40 
2  60 
3  80 
Ran: #2 
Test: num85 
1  14 
2  15 
3  16 

我使用strsplit功能如下尝试:

header = readLines("C:/My Documents/DVH Test.txt", n=17) 
data = read.table("C:/My Documents/DVH Test.txt", skip=16, 
col.names = c("bin", "value")) 

data.split = strsplit(data, "R") 

我不知道如果我即使使用正确的方法。

任何建议,将不胜感激。

在此先感谢。

好吧,我已经试过这一点,但我发现了一个空载体和元素不排队像你:

data = scan("C:/My Documents/DV.txt", what="raw") 

dat = readLines(textConnection(data)) 
dat = dat[!grepl("Ran",dat)] 
dat.split = lapply(split(dat,cumsum(grepl("Test:",dat))), 
    function(x) 
     read.table(text=x,header=TRUE)) 

回答

1

试试这个,例如:

txt ='Ran: Efg$ 
Test: num85 
1  50 
2  52 
3  54 
Ran: pg2 
Test: num85 
1  40 
2  60 
3  80 
Ran: #2 
Test: num85 
1  14 
2  15 
3  16' 
## read all lines 
ll <- readLines(textConnection(txt)) 
## remove "Ran"'s lines 
ll <- ll[!grepl('Ran',ll)] 
## split list in each headr an read it using 
## read.table(text=...) 
lapply(split(ll,cumsum(grepl("Test:",ll))), 
     function(x) 
     read.table(text=x,header=TRUE)) 

这给data.frame的名单:

$`1` 
    Test. num85 
1  1 50 
2  2 52 
3  3 54 

$`2` 
    Test. num85 
1  1 40 
2  2 60 
3  3 80 

$`3` 
    Test. num85 
1  1 14 
2  2 15 
3  3 16 
+0

您好,感谢您的解决方案,但我似乎无法得到的元素来排队,我得到了一个空载体。我上面做了一些编辑。有什么建议么? – crazian