2013-01-02 62 views
-5

我想1个文件的一些行连接成1列,但它必须依赖于内容,是整个文件变量。连接具有条件

我的数据文件的简化版本:

>xy|number|Name 
ABCABCABC 
ABCABCABC 
ABCABCABC 
ABC 
>xy|number2|Name2 
ABCABCABC 
ABCABC 
>xy|number3|Name3 
ABCABCABC 
ABCABCABC 
ABCABCABC 
ABCAB 

我希望它在像这样结束:(空间意味着不同的列)

xy number Name ABCABCABCABCABCABCABCABCABCABC 
xy number2 Name2 ABCABCABCABCABC 
xy number3 Name3 ABCABCABCABCABCABCABCABCABCABCAB 
+0

我敢肯定,这可以在R上完成,但它几乎可以肯定是错误的语言为任务(和你有什么打算用这些结构中的R办?)。如果他想要做后期处理,R,并且该文件是不是巨大的考虑命令式语言如Perl或C. –

+0

@MatthewLUndberg,我不明白为什么R是错误的语言来做到这一点。 – nograpes

+0

@nograpes只是一个猜测。 –

回答

4

这里是一个类似的解决方案,以@ MatthewLundberg,但使用cumsum来分割向量。

file<-scan('~/Desktop/data.txt','character') 
h<-grepl('^>',file) 
file[h]<-gsub('^>','',paste0(file[h],'|'),'') 
l<-split(file,cumsum(h)) 
do.call(rbind,strsplit(sapply(l,paste,collapse=''),'[|]')) 

# [,1] [,2]  [,3] [,4]        
# 1 "xy" "number" "Name" "ABCABCABCABCABCABCABCABCABCABC" 
# 2 "xy" "number2" "Name2" "ABCABCABCABCABC"     
# 3 "xy" "number3" "Name3" "ABCABCABCABCABCABCABCABCABCABCAB" 
+0

+1。非常好.. –

+0

确保在这里,'file'不是一个因素。 –

+1

我只是写了一些类似的东西,但第二行和第四行解压缩......现在没有意义了......用'scan','what = character()'读取文件,这将是一个完整的答案拥有。 – John

2
dat <- read.table(file, header=FALSE) 

h <- grep('^>', dat$V1) 
m <- matrix(c(h, c(h[-1]-1, length(dat$V1))), ncol=2) 
gsub('[|]', ' ', 
     sub('>', '', 
     apply(m, 1, function(x) 
      paste(dat$V1[x[1]], paste(dat$V1[(x[1]+1):x[2]], collapse='')) 
      ) 
     ) 
    ) 
## [1] "xy number Name ABCABCABCABCABCABCABCABCABCABC"  
## [2] "xy number2 Name2 ABCABCABCABCABC"     
## [3] "xy number3 Name3 ABCABCABCABCABCABCABCABCABCABCAB" 
+0

不知何故,我在这里失去了号码和名字,但你给了我很多很棒的信息,谢谢! – user1941884

+0

糟糕,我的坏。它完美的工作,谢谢你! – user1941884

0

东西供你考虑的情况下,要与结果data.frame:

raw <- ">xy|number|Name 
ABCABCABC 
ABCABCABC 
ABCABCABC 
ABC 
>xy|number2|Name2 
ABCABCABC 
ABCABC 
>xy|number3|Name3 
ABCABCABC 
ABCABCABC 
ABCABCABC 
ABCAB" 

s <- readLines(textConnection(raw))  # s is vector of strings 

first.line <- which(substr(s,1,1) == ">") # find first line of set 
N <- length(first.line) 
first.line <- c(first.line, length(s)+1) # add first line past end 

# Preallocate data.frame (good idea if large) 
d <- data.frame(X1=rep("",N), X2=rep("",N), X3=rep("",N), X4=rep("",N), 
       stringsAsFactors=FALSE) 

for (i in 1:N) 
{ 
    w <- unlist(strsplit(s[first.line[i]],">|\\|")) # Parse 1st line 
    d$X1[i] <- w[2] 
    d$X2[i] <- w[3] 
    d$X3[i] <- w[4] 
    d$X4[i] <- paste(s[ (first.line[i]+1) : (first.line[i+1]-1) ], collapse="") 
} 


d 
    X1  X2 X3        X4 
1 xy number Name ABCABCABCABCABCABCABCABCABCABC 
2 xy number2 Name2     ABCABCABCABCABC 
3 xy number3 Name3 ABCABCABCABCABCABCABCABCABCABCAB 

我希望在默认情况下[R左对齐的字符串时,它会显示他们在一个data.frame。