1

Say I have this data frame:

> df = structure(list(one = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("A", "B"),class = "factor"), two = 1:6),.Names = c("one", "two"),row.names = c(NA, -6L),class = "data.frame")

> df

  one two
1   A   1
2   A   2
3   A   3
4   B   4
5   B   5
6   B   6

And want to reshape it to this:

A  B
1  4
2  5
3  6

You can assume that there are an equal number of rows for each unique element in column "one".

I'm able to do it as follows:

library(tidyr)
df = cbind(df,index=c(1:3,1:3))
spread(df,key = one,value= two)[,-1]

However, this feels like a bit of a hack because it uses data reshaping functions that assume that the resulting rows are observations and that the values for each row have some relationship. In this solution I made up this relationship by adding indices that allow the reshaping to take place the way I want. Which then requires me to remove that additional information. Doesn't feel clean.

So my question is, is there a function or simple one-liner that does what I want in a more direct way?

Patrick
  • 513
  • 4
  • 14

1 Answers1

1

We can use unstack

unstack(df, two~one)
#  A B
#1 1 4
#2 2 5
#3 3 6
akrun
  • 874,273
  • 37
  • 540
  • 662