0

I have a data frame with 1000+ rows and the following R code creates a similar data frame:

df = data.frame(yr = rep(1:3, 2), 
                name=c(rep("c1", 3), rep("c2", 3)),
                ms=c(101,102,103,301, 302,303),
                td=c(201,202,203,401,402,403))

As we can see, yr column indicates timeline, name column indicates repeating id with ms and td values of certain attributes. Similar structures are quite common in Economics. I would like to unstack sections of the data frame based on name column. The final output should look like:

yr c1_ms c1_td c2_ms c2_td
 1   101   201   301   401
 2   102   202   302   402
 3   103   203   303   403

I tried dplyr::spread but couldn't get any solution as it seems to work with one column only. What will be a R-ish way of getting this desired data layout without resorting to for loops?

Appreciate the help very much.

kishore
  • 541
  • 1
  • 6
  • 18
  • Using base R's `reshape` function, for example, you could do `reshape(df, direction="wide", idvar="yr", timevar="name")`. – lmo May 23 '17 at 18:33
  • @lmo, thanks for the quick answer. Appreciate it very much. – kishore May 24 '17 at 02:54

0 Answers0