OverFlow Police
OverFlow Police

Reputation: 861

reshape a matrix in R and converting every n rows into one row

I have a data frame df like:

year     location
1           A
2           B
3           C
------------------
1           X
5           A
10          F
------------------
3          F
5          x
2          y

I would like to reshape it to

year_1  location_1     year_2   location_2    year_3  location_3
1         A             2         B               3      F
3         C             1         X               5      X
5         A             10        F               2      Y

I can do a hack, and concatenate the first two columns, and do

d <- matrix(df, nrow = 70, byrow = FALSE)

But again later I have to split the concatenated stuff, is there a neat way of doing this?

Upvotes: 0

Views: 298

Answers (1)

IRTFM
IRTFM

Reputation: 263301

How about splitting and recombinining:

 wide.df <- Reduce(cbind, split(df, cumsum( rep(c(1,0,0), nrow(df)/3) ) )

This would have the advantage over coercion to matrix and back-coercion to dataframe that it would not have any difficulty with factor or characters messing up the classes. Using a matrix as an intermediate would first loose all the levels and if you had both characters and factors you would have a really confusing mess.

You might need to fiddle with column names a bit if you needed the exact result and I'd be happy to assist in that if you posted a copy-pasteable [MCVE]

Upvotes: 1

Related Questions