1

I want to aggregate a table data. I have data as below.

x                y
served           4d0e1e88-60a4-4e9e-f914-50fab6039d73
close            6ad31901-ed0d-4a12-a686-962bbd473018
served           6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
served           6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473019
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
Click            6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
Click            6ad31901-ed0d-4a12-a686-962bbd473014

I am trying to aggregate this as shown below.

y                                 Click   close  served switchProduct
4d0e1e88-60a4-4e9e-f914-50fab6039d73            1   
6ad31901-ed0d-4a12-a686-962bbd473014    1           
6ad31901-ed0d-4a12-a686-962bbd473018    1   1   2   3
6ad31901-ed0d-4a12-a686-962bbd473019                1

But on trying to get the above expected output am getting this output

aggregate(x$x,list(x$x,x$y),length)

y                                   x
4d0e1e88-60a4-4e9e-f914-50fab6039d73    1
6ad31901-ed0d-4a12-a686-962bbd473014    1
6ad31901-ed0d-4a12-a686-962bbd473018    7
6ad31901-ed0d-4a12-a686-962bbd473019    1
tonytonov
  • 25,060
  • 16
  • 82
  • 98
sandeep
  • 31
  • 2
  • 9

1 Answers1

1

You probably want to use table rather than aggregate.

d <- read.table(text='x                y
served           4d0e1e88-60a4-4e9e-f914-50fab6039d73
close            6ad31901-ed0d-4a12-a686-962bbd473018
served           6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
served           6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473019
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
Click            6ad31901-ed0d-4a12-a686-962bbd473018
switchProduct    6ad31901-ed0d-4a12-a686-962bbd473018
Click            6ad31901-ed0d-4a12-a686-962bbd473014', header=TRUE)

t(table(d))

                                      x
y                                      Click close served switchProduct
  4d0e1e88-60a4-4e9e-f914-50fab6039d73     0     0      1             0
  6ad31901-ed0d-4a12-a686-962bbd473014     1     0      0             0
  6ad31901-ed0d-4a12-a686-962bbd473018     1     1      2             3
  6ad31901-ed0d-4a12-a686-962bbd473019     0     0      0             1
jbaums
  • 27,115
  • 5
  • 79
  • 119
  • I have a data with 21 variables out of that i need above two variables so i have sent only two variables. but i will try your method and come to you. thanks – sandeep Feb 19 '14 at 07:13
  • How can i save this to a data frame. is it possible to save this into data frame. t(table(d)) – sandeep Feb 20 '14 at 06:23
  • Try `as.data.frame.matrix(t(table(d)))` (courtesy of [@VictorVanHee](http://stackoverflow.com/a/10759011/489704)) – jbaums Feb 20 '14 at 07:25