-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

我希望默认情况下 R 左对齐的字符串在 data.frame 中显示它们时。

于 2013-01-02T07:12:55.703 回答