-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
4

3 に答える 3

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"
于 2013-01-02T04:41:08.443 に答える
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"
于 2013-01-02T03:54:05.990 に答える
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

data.frameに表示するときに、デフォルトでRの左寄せ文字列が必要です。

于 2013-01-02T07:12:55.703 に答える