-2

I have a table in a file. There is a character line before the table starts. The table in a file looks like this

XYZ=1
1 40 3 24 4
2 40 4 16 21
3 40 3 12 16
XYZ=2
1 40 5 27 8
2 40 4 16 21
3 40 2 14 24

I want to have output with replicating all rows. For example Row 1 to Row 3 should repeat themselves and the resulting table should have 6 rows in total. The output should look something like this -

XYZ=1
1 40 3 24 4
2 40 4 16 21
3 40 3 12 16
4 40 3 24 4
5 40 4 16 21
6 40 3 12 16
XYZ=2
1 40 5 27 8
2 40 4 16 21
3 40 2 14 24
4 40 5 27 8
5 40 4 16 21
6 40 2 14 24

I am new to R. It will be great if someone help me with this problem.

1 Answers1

0

This should do it. It definitely isn't the cleanest way to do it, but from a beginners point of view the functions are pretty basic. test_table.txt is the same data you gave in the beginning. I don't create any lists and the output looks like

> output
         [,1] [,2] [,3] [,4] [,5]
XYZ = 1    1   40    3   24    4
           2   40    4   16   21
           3   40    3   12   16
XYZ = 2    1   40    3   24    4
           2   40    4   16   21
           3   40    3   12   16
XYZ = 3    1   40    5   27    8
           2   40    4   16   21
           3   40    2   14   24
XYZ = 4    1   40    5   27    8
           2   40    4   16   21
           3   40    2   14   24

data <- readLines("test_table.txt")

get_rid <- which(unlist(strsplit(data, split = "=")) == "XYZ")
new_data <- data[-c(get_rid[1], get_rid[2:length(get_rid)]-1)]

output <- matrix(nrow = 1, ncol = 5)
for ( i in 1 : length(new_data) ) {
    temp <- unlist(strsplit(new_data[i], " "))
    if ( temp[1] == 1 && i != 1 ) {
        c <- length(output[,1]) 
        output <- rbind(output, output[(c-output[(c-1),1]):(output[c,1]+1),])

        ##output <- rbind(output, output[(i-output[(i-1),1]):(output[(i),1]+1),])
        output <- rbind(output, as.numeric(temp))
    } else {
        output <- rbind(output, as.numeric(temp))
    }
    if ( i == length(new_data) ) {
        output <- rbind(output, output[max(which(output[,1] == 
           1)):length(output[,1]),])
    }
}
output <- output[2:length(output[,1]),]

xyz_names <- character(length(output[,1]))
c <- 1
for ( i in 1 : length(output[,1]) ) {
    if ( output[i,1] == 1 ) {
    xyz_names[i] <- paste("XYZ =", c, collapse = "")
    c <- c + 1
    } else {
        xyz_names[i] <- ""
    }
}

rownames(output) <- xyz_names
##the values of XYZ = ... is
which(output[,1] == 1)
output
Rex
  • 96
  • 6