S Das
S Das

Reputation: 3391

reshape of a large data

I have a large dataset with 100 variables and 400,000 transactions. Here's a sample data:

a <- structure(list(ID = c("A1", "A2", "A3", "A1", "A1", "A2", "A4", "A5", "A2", "A3"), 
Type = c("A", "B", "C", "A", "A", "A", "B", "B", "C", "B"), 
Alc = c("E", "F", "G", "E", "E", "E", "F", "F", "F", "F"), 
Com = c("Y", "N", "Y", "N", "Y", "Y", "Y", "N", "N", "Y")),
.Names = c("ID", "Type", "Alc", "Com"), row.names = c(NA, -10L), class = "data.frame")
a

   ID Type Alc Com
1  A1    A   E   Y
2  A2    B   F   N
3  A3    C   G   Y
4  A1    A   E   N
5  A1    A   E   Y
6  A2    A   E   Y
7  A4    B   F   Y
8  A5    B   F   N
9  A2    C   F   N
10 A3    B   F   Y

I like to get the dataset like this:

ID      Type_A  Type_B  Type_C  Alc_E   Alc_F   Alc_G   Com_Y   Com_N
A1           3      0        0      3       0       0       2       1
A2           1      1        1      1       2       0       1       2
A3           0      1        1      0       1       1       2       0
A4           0      1        0      0       1       0       1       0
A5           0      1        0      0       1       0       0       1

I am using 'dcast' function from 'reshape2' package. But the results are not according to my requirement.

Thanks in advance.

Upvotes: 2

Views: 773

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193677

Since you seem to just be tabulating each column with respect to a$ID, you can also just use table within lapply, like this:

do.call(cbind, lapply(a[-1], function(x) table(a[[1]], x)))
#    A B C E F G N Y
# A1 3 0 0 3 0 0 1 2
# A2 1 1 1 1 2 0 2 1
# A3 0 1 1 0 1 1 0 2
# A4 0 1 0 0 1 0 0 1
# A5 0 1 0 0 1 0 1 0

The names aren't nearly as pretty, but it is easy to customize your lapply command to fix that:

do.call(cbind, 
        lapply(names(a[-1]), function(x) {
          temp <- table(a[[1]], a[[x]])
          colnames(temp) <- paste(x, colnames(temp), sep = "_")
          temp
        }))
#    Type_A Type_B Type_C Alc_E Alc_F Alc_G Com_N Com_Y
# A1      3      0      0     3     0     0     1     2
# A2      1      1      1     1     2     0     2     1
# A3      0      1      1     0     1     1     0     2
# A4      0      1      0     0     1     0     0     1
# A5      0      1      0     0     1     0     1     0

Upvotes: 2

Arun
Arun

Reputation: 118879

Assuming your data.frame is DF:

require(reshape2)
dcast(melt(DF, id.var=c("ID")), ID ~ variable + value, value.var="value")

Aggregation function missing: defaulting to length
  ID Type_A Type_B Type_C Alc_E Alc_F Alc_G Com_N Com_Y
1 A1      3      0      0     3     0     0     1     2
2 A2      1      1      1     1     2     0     2     1
3 A3      0      1      1     0     1     1     0     2
4 A4      0      1      0     0     1     0     0     1
5 A5      0      1      0     0     1     0     1     0

Upvotes: 5

Related Questions