Reputation: 1
year
ID 2005 2006 2007 2008 2009 2010 2011 2012
Altstadt/Nord 17821 17947 17764 17301 17211 17337 17421 17330
Altstadt/Süd 26706 26778 26693 26218 26657 26443 26677 26722
Bayenthal 8117 8388 8411 8455 8479 8834 8981 8911
Bickendorf 16350 16303 16383 16321 16351 16429 16692 16813
I have created this table using: xtabs(Einwohneranzahl~raum+jahr,subsetHH)
.
Now i want it as a subset in order to derive an addition column (average on all years).
Upvotes: 0
Views: 42
Reputation: 21400
If speed of execution is not an issue (rowSums
, rowMeans
are faster), you can also use apply
(using @GKi's data) as well as sum
(if you want to add up the values):
x$new <- apply(x[-1], 1, sum)
Result:
x
ID X2005 X2006 X2007 X2008 X2009 X2010 X2011 X2012 new
1 Altstadt/Nord 17821 17947 17764 17301 17211 17337 17421 17330 140132
2 Altstadt/Süd 26706 26778 26693 26218 26657 26443 26677 26722 212894
3 Bayenthal 8117 8388 8411 8455 8479 8834 8981 8911 68576
4 Bickendorf 16350 16303 16383 16321 16351 16429 16692 16813 131642
If it is the average you want to compute replace sum
by mean
.
Upvotes: 0
Reputation: 39647
You can use rowMeans
to add a mean over all years like:
x$Mean <- rowMeans(x[-1])
x
# ID X2005 X2006 X2007 X2008 X2009 X2010 X2011 X2012 Mean
#1 Altstadt/Nord 17821 17947 17764 17301 17211 17337 17421 17330 17516.50
#2 Altstadt/Süd 26706 26778 26693 26218 26657 26443 26677 26722 26611.75
#3 Bayenthal 8117 8388 8411 8455 8479 8834 8981 8911 8572.00
#4 Bickendorf 16350 16303 16383 16321 16351 16429 16692 16813 16455.25
Data:
x <- read.table(header=TRUE, text=" ID 2005 2006 2007 2008 2009 2010 2011 2012
Altstadt/Nord 17821 17947 17764 17301 17211 17337 17421 17330
Altstadt/Süd 26706 26778 26693 26218 26657 26443 26677 26722
Bayenthal 8117 8388 8411 8455 8479 8834 8981 8911
Bickendorf 16350 16303 16383 16321 16351 16429 16692 16813")
Upvotes: 1
Reputation: 198
The rowSums() function can do this. It's a bit easier if you turn it into a data frame first.
library(dplyr)
# Make Cross tab and turn into data frame
cross_tab <- as.data.frame(xtabs(Einwohneranzahl~raum+jahr,subsetHH))
# Add a column that is the sum of each row
mutate(cross_tab, all_years = rowSums(cross_tab))
Upvotes: 0