-1

I have been trying to get this right but i cant find the right way to apporach this problem. Lets say i have some data that look like this:

hhid   totalplacevisited
1              5
1              6
1              2
2              2
2              4
3              1  

How can i aggregate the data so i can get values in this format:

hhid   totalplacevisited   totalplacedvisitedbyhh
1              5                    13
1              6                    13
1              2                    13
2              2                    6
2              4                    6 
3              1                    1
Daniel
  • 5,095
  • 5
  • 35
  • 48

3 Answers3

1

One alternative is using ave

> transform(df, totalplacedvisitedbyhh = with(df,ave(totalplacevisited, hhid, FUN=sum)))
  hhid totalplacevisited totalplacedvisitedbyhh
1    1                 5                     13
2    1                 6                     13
3    1                 2                     13
4    2                 2                      6
5    2                 4                      6
6    3                 1                      1

Other alternative is using data.table

> library(data.table)
> DT <- data.table(df)
> DT[, totalplacedvisitedbyhh := sum(totalplacevisited), by=hhid]
> DT
   hhid totalplacevisited totalplacedvisitedbyhh
1:    1                 5                     13
2:    1                 6                     13
3:    1                 2                     13
4:    2                 2                      6
5:    2                 4                      6
6:    3                 1                      1
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
1

The data.table package is the fastest way:

dt = data.table(df)
dt[,totalplacesvisitedbyhh:=sum(totalplacevisited),by=hhid]
Señor O
  • 17,049
  • 2
  • 45
  • 47
0

Here is the solution from plyr package

library(plyr)
ddply(mydf,.(hhid),transform, totalplacedvisitedbyhh=sum(totalplacevisited))

 hhid totalplacevisited totalplacedvisitedbyhh
1    1                 5                     13
2    1                 6                     13
3    1                 2                     13
4    2                 2                      6
5    2                 4                      6
6    3                 1                      1
Metrics
  • 15,172
  • 7
  • 54
  • 83