1

My data frame looks like this:

 x <- data.frame(c("a","a","a","a","b","b","c","c","c","a", "a"), c(1,2,3,4,1,2,1,2,3, 1, 2))
names(x) <- c("id","nr") 

      id      nr
   1   a       1
   2   a       2
   3   a       3
   4   a       4
   5   b       1
   6   b       2
   7   c       1
   8   c       2
   9   c       3
   10  a       1
   11  a       2

I want to have something like this:

  id   1  2  3  4
   a   1  2  3  4
   a   1  2  NA NA
   b   1  2  NA NA
   c   1  2  3  NA

I already used dcast(x, id ~ nr, value.var ="nr") but I got the warning:

"Aggregation function missing: defaulting to length".

I understand that this is due to non-unique rows. Also I created groups which give me the results above. But is there a way to create it without having to create groups?

x <- data.frame(c("a","a","a","a","b","b","c","c","c","a", "a"), 
c(1,1,1,1,1,1,1,1,1,2,2), c(1,2,3,4,1,2,1,2,3, 1, 2))
names(x) <- c("id", "group","nr")

dcast(x, id + group ~ nr, value.var = "nr")
User7598
  • 1,658
  • 1
  • 15
  • 28
Dat Tran
  • 2,368
  • 18
  • 25
  • What's the question? The warning happens because you don't specify argument fun.aggregate . . – vagabond May 07 '15 at 18:33
  • oh yes, i see - for every id value , OP wants a new row for unique combinations of NR values.. – vagabond May 07 '15 at 18:41
  • Related: [*dcast error: ‘Aggregation function missing: defaulting to length’*](https://stackoverflow.com/q/33051386/2204410) – Jaap Aug 31 '18 at 05:46

1 Answers1

4

You may need a grouping variable. Instead of creating it manually as showed in the example, we can use rleid and then try with dcast from the devel version of data.table. i.e. v1.9.5+. Instructions to install the devel version are here

library(data.table)
dcast(setDT(x)[, gr:=rleid(id)], id+gr~nr, value.var='nr')[,gr:=NULL][]
#   id 1 2  3  4
#1:  a 1 2  3  4
#2:  a 1 2 NA NA
#3:  b 1 2 NA NA
#4:  c 1 2  3 NA

Or as @Arun mentioned in the comments, we can do this directly within the dcast itself

dcast(setDT(x), id + rleid(id) ~ nr, value.var = 'nr')[,id_1:= NULL]
akrun
  • 874,273
  • 37
  • 540
  • 662