KT_1
KT_1

Reputation: 8494

Summarise/reshape data in R

For an example dataframe:

df <- structure(list(id = 1:18, region = structure(c(1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("a", 
"b"), class = "factor"), age.cat = structure(c(1L, 1L, 2L, 2L, 
2L, 3L, 3L, 4L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 4L, 4L, 4L), .Label = c("0-18", 
"19-35", "36-50", "50+"), class = "factor")), .Names = c("id", 
"region", "age.cat"), class = "data.frame", row.names = c(NA, 
-18L))

I want to reshape the data, as detailed below:

region 0-18 19-35 36-50 50+
a      2    3     2     1
b      4    2     1     3

Do I simply aggregate or reshape the data? Any help would be much appreciated.

Upvotes: 1

Views: 67

Answers (2)

Raphael K
Raphael K

Reputation: 2353

Using reshape2:

install.packages('reshape2')
library(reshape2)

df1 <- melt(df, measure.vars = 'age.cat')
df1 <- dcast(df1, region ~ value)

Upvotes: 2

DatamineR
DatamineR

Reputation: 9628

You can do it just using table:

 table(df$region, df$age.cat)

    0-18 19-35 36-50 50+
  a    2     3     2   1
  b    4     2     1   3

Upvotes: 6

Related Questions