0

I have data in the following format:

df1 <- cbind(allnames = c("id","descx","descy","descz","id","descx","descy","descz","id","descx","descy","descz"), 
             allvalues = c(100,"aaa","bbb", "ccc", 200,"ddd","eee", "fff",300,"ggg","hhh", "iii"))
> df1
  allnames allvalues
 [1,] "id"     "100"    
 [2,] "descx"  "aaa"    
 [3,] "descy"  "bbb"    
 [4,] "descz"  "ccc"    
 [5,] "id"     "200"    
 [6,] "descx"  "ddd"    
 [7,] "descy"  "eee"    
 [8,] "descz"  "fff"    
 [9,] "id"     "300"    
[10,] "descx"  "ggg"    
[11,] "descy"  "hhh"    
[12,] "descz"  "iii"

I would like to Pivot/Transform df1 to the following format:

     id    descx descy descz
[1,] "100" "aaa" "bbb" "ccc"
[2,] "200" "ddd" "eee" "fff"
[3,] "300" "ggg" "hhh" "iii"

I tried reshape2 and tidyr libraries to Pivot/Transform df1 in vain. I also checked and tested suggestion form these and other postings (R: Pivoting using 'spread' function; Pivot table on R using `dplyr` or `tidyr`; Using R, how to pivot/transform a dataset whose elements are the result of a function;) in this forum but could not get the output I needed. Any advice to accomplish my need please?

RanonKahn
  • 853
  • 10
  • 34
  • From reshape2: `dcast(as.data.frame(cbind(v = rep(1:3, each=4), df1)), v ~ allnames, value.var = "allvalues")` – Frank Aug 04 '17 at 19:00
  • 3
    A bit shorter with base R's `unstack`: `unstack(as.data.frame(df1), allvalues ~ allnames)`. You'd still have to rearrange the variables as their sorted alphabetically. – lmo Aug 04 '17 at 19:03
  • @lmo Should we reopen so you can post that? It's a good answer and I'm not sure it fits in the dupe target. – Frank Aug 04 '17 at 19:08
  • 1
    @Frank There's an `unstack` answer in the dupe, so it's probably OK to leave this as is. – lmo Aug 04 '17 at 19:11
  • @Frank, I wonder how I missed the earlier post. Should I delete the question? – RanonKahn Aug 04 '17 at 19:20
  • Nope, I think it's good to keep it. You missed it because you searched using terms like "pivot" instead of "reshape". By keeping your post here, others who search like you did will be able to follow it to that post. – Frank Aug 04 '17 at 19:56

0 Answers0