user2171177
user2171177

Reputation: 75

Data Transformations in R

I have a need to look at the data in a data frame in a different way. Here is the problem..

I have a data frame as follows

Person  Item  BuyOrSell
1        a    B
1        b    S
1        a    S
2        d    B
3        a    S
3        e    S

I need it be transformed into this way. Show the sum of all transactions made by the Person on individual items.

Person   a   b    d   e
1        2   1    0   0
2        0   0    1   0
3        1   0    0   1

I was able to achieve the above by using the

table(Person,Item) in R

The new requirement I have is to see the data as follows. Show the sum of all transactions made by the Person on individual items broken by the transaction type (B or S)

Person    aB   aS   bB   bS   dB   dS   eB   eS
1          1    1    0    1    0    0   0     0
2          0    0    0    0    1    0   0     0
3          1    0    0    0    0    0   0     1

So i created a new column and appended the values of both the Item and BuyOrSell.

df$newcol<-paste(Item,"-",BuyOrSell,sep="")
table(Person,newcol) 

and was able to achieve the above results.

Is there a better way in R to do this type of transformation ?

Upvotes: 3

Views: 409

Answers (1)

Blue Magister
Blue Magister

Reputation: 13363

Your way (creating a new column via paste) is probably the easiest. You could also do this:

require(reshape2)
dcast(Person~Item+BuyOrSell,data=df,fun.aggregate=length,drop=FALSE)

Upvotes: 1

Related Questions