R:如何按部分分隔外部文本数据

时间:2014-04-01 15:38:08

标签: c# regex r strsplit

我有一个来自文本文件的数据集,该数据集只有2列但数据中有多个分节符,我想将它放入单独的数组中,其中数组的名称是与#34相邻的第2列中的文本;冉:&#34 ;.下面是一个示例数据集:

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 个答案:

答案 0 :(得分: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