1

我有一个包含 2940 行的 txt 文件,其中模式每 10 行出现一次(即,从第 1 行到第 10 行对应于对象 1 ...等)。

以下是一些示例行:

[1] 1254 0 40 1 1 0 0
[1] -9 2 140 0 289 -9 -9 -9
[1] 0 -9 -9 0 12 16 84 0
[1] 0 0 0 0 150 18 -9 7
[1] 172 86 200 110 140 86 0 0
[1] 0 -9 26 20 -9 -9 -9 -9
[1] -9 -9 -9 -9 -9 -9 -9 12
[1] 20 84 0 -9 -9 -9 -9 -9
[1] -9 -9 -9 -9 -9 1 1 1
[1] 1 1 -9. -9. name    # whenever you see the word "name", that's the stop of one pattern
[1] 1255 0 49 0 1 0 0
[1] -9 3 160 1 180 -9 -9 -9
[1] 0 -9 -9 0 11 16 84 0
[1] 0 0 0 0 -9 10 9 7
[1] 156 100 220 106 160 90 0 0
[1] 1 2 14 13 -9 -9 -9 -9
[1] -9 -9 -9 -9 -9 -9 -9 11
[1] 20 84 1 -9 -9 2 -9 -9
[1] -9 -9 -9 -9 -9 1 1 1
[1] 1 1 -9. -9. name           # another stop
1848 Levels: -9 -9 -9 -9 -9 -9 -9 -9 ... 99 85 170 105 160 95 1 0

我用代码创建了这个

data = read.table(file,header = T, sep = "\n")

当我尝试创建一个每 10 行连接一次的循环时,

while (j < 2940){
    for (index in 1:294){
        new_data[index] = cbind(data1[a,],data1[b,],data1[c,],data1[d,],data1[e,],
            data1[f,],data1[g,],data1[h,],data1[i,], data1[j,])
        a = a +10
        b = b +10
        c = c +10
        d = d +10
        e = e +10
        f = f +10
        g = g +10
        h = h +10
        i =  i +10
        j = j +10
            }
}

输出将行中的数字相加。例如,第 1 行变为 1323。

基本上,我想将 txt 文件重新组织成如下内容:

1254 0 40 1 1 0 0 -9 2 140 0 289 -9 -9 -9 0 -9 -9 0 12 16 84 0 0 0 0 0 150 18 -9 7 172 86 200 110 140 86 0 0 0 -9 26 20 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 12 20 84 0 -9 -9 -9 -9 -9 -9 -9 -9 -9 -9 1 1 1 1 1 -9. -9. name

这是 73 列的 1 行,之后是类似的行。

这是一个 dput() 以备不时之需:https ://codeshare.io/5Dy4EW

4

1 回答 1

0

这是一个使用 readLines 函数的潜在解决方案,然后每 10 行数据循环一次。该separate函数的结果是数据框,其中一列包含所有 76 个数字/“名称”。

#read file in by individual lines
file<-readLines("test.txt")

#find the rows with the end of pattern
endofpattern<-grep("name", file)

#Create vector of collapse strings
answer<-sapply(endofpattern, function(i) {
  paste(file[(i-9):(i)], collapse = " ")
})

#create data frame and divide into columns
library(tidyr)
separate(data.frame(answer), col=answer, into=paste0("C", 1:76))



    C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 C16 C17 C18 C19 C20 C21 C22 C23 C24 C25 C26 C27 C28 C29 C30 C31 C32 C33 C34 C35 C36 C37
1 1254  0 40  1  1  0  0  9  2 140   0 289   9   9   9   0   9   9   0  12  16  84   0   0   0   0   0 150  18   9   7 172  86 200 110 140  86
2 1255  0 49  0  1  0  0  9  3 160   1 180   9   9   9   0   9   9   0  11  16  84   0   0   0   0   0   9  10   9   7 156 100 220 106 160  90
于 2020-03-10T19:44:09.287 回答