Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Transformations in R

Tags:

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 ?

like image 963
user2171177 Avatar asked Jun 27 '26 12:06

user2171177


1 Answers

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)
like image 136
Blue Magister Avatar answered Jun 29 '26 01:06

Blue Magister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!