Wolfone
Wolfone

Reputation: 1436

How to aggregate by one column to build rows while aggregation in other columns transforms into new columns?

I am rather new to R and I am still unable to solve a certain aggregation problem; I have information of this form:

SubjectType   Subtype
---------------------
TypeA            1
TypeB            2
TypeC            1
TypeB            1
TypeA            1

And I want to transform this into the following form:

SubjectType   #(Subtype=1)  #(Subtype=2)
---------------------------------------- 
TypeA              2             0
TypeB              1             1
TypeC              1             0

I tried to achieve this by using the aggregate-function but I failed so far. Can this even be done with a single aggregate(...) ?

Upvotes: 1

Views: 17

Answers (1)

Wolfone
Wolfone

Reputation: 1436

I achieved what I was looking for by using the library dplyr.

library(dplyr);

subtype1 <- myData %>% group_by(myData$SubjectType) %>% summarize(subtype1 = sum(Subtype==1));
subtype2 <- myData %>% group_by(myData$SubjectType) %>% summarize(subtype1 = sum(Subtype==2));

merge(subtype1, subtype2);

Upvotes: 1

Related Questions