Rearranging a data frame from row id to column id

Viewed 49

Lets say I have a data frame created as

id <- c("a","b","c","d","e","f")
a <- c(6,4,3,6,4,9)
b <- c(8,5,2,9,0,1)

df <- cbind.data.frame(id,a,b)

which gives the output as

   id x y
1  a 6 8
2  b 4 5
3  c 3 2
4  d 6 9
5  e 4 0
6  f 9 1

This is of course a smaller reproducible version of my actual problem. In my actual scenario I have created a data frame from multiple .xlsx files in the following manner

files <- list.files(path = "Discharge", pattern = "*_SUMQH.xls", full.names = T)

strm_data <- sapply(files, read_xlsx, simplify=FALSE) %>% 
  bind_rows(.id = "id")

strm_data <- as.data.frame(strm_data[,-(7:19)])
strm_data <- na.omit(strm_data)

row.names(strm_data) <- NULL

What I want is to arrange the data frame in the following manner

  id x y  id x y id x y id x y  id x y id x y
1 a  6 8  b  4 5  c 3 2 d  6 9  e  4 0  f 9 1
2 Answers

Try the base R code below, using cbind + split

> do.call(cbind, unname(split(df, 1:nrow(df))))
  id a b id a b id a b id a b id a b id a b
1  a 6 8  b 4 5  c 3 2  d 6 9  e 4 0  f 9 1

Here is really basic solution:

cbind(df[1,], df[2,], df[3,], df[4,], df[5,], df[6,])

Output:

  id x y id x y id x y id x y id x y id x y
1  a 6 8  b 4 5  c 3 2  d 6 9  e 4 0  f 9 1
Related