'Convert every n # of rows to columns and stack them in R?

I have a tab-delimited text file with a series of timestamped data. I've read it into R using read.delim() and it gives me all the data as characters in a single column. Example:

df <- data.frame(c("2017","A","B","C","2018","X","Y","Z","2018","X","B","C"))
colnames(df) <- "col1"
df

I want to convert every n # of rows (in this case 4) to columns and stack them without using a for loop. Desired result:

col1 <- c("2017","2018","2018")
col2 <- c("A","X","X")
col3 <- c("B","Y","B")
col4 <- c("C","Z","C")
df2 <- data.frame(col1, col2, col3, col4)
df2

I created a for loop, but it can't handle the millions of rows in my df. Should I convert to a matrix? Would converting to a list help? I tried as.matrix(read.table()) and unlist() but without success.



Solution 1:[1]

The easiest way would be to create a matrix with matrix(ncol=x, byrow=TRUE), then convert back to data.frame. Should be quite fast too.

df |>
        unlist() |>
        matrix(ncol=4, byrow = TRUE) |>
        as.data.frame() |>
        setNames(paste0('col', 1:4))

  col1 col2 col3 col4
1 2017    A    B    C
2 2018    X    Y    Z
3 2018    X    B    C

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GuedesBF