r - Calculating item frequencies from single column -
i have set of data transaction id has @ least 1 item both , b. want calculate frequencies items category tabulated respect of category b.
input looks like:
id = c(1,1,2,2,2,2,3,3,3,3) cat = c("a","b","a","a","a","b","b","a","a","b") item = c("item 1","item 30","item 2","item 3", "item 1","item 30","item 31","item 1","item 2","item 32") df = data.frame(id,cat,item) id cat item 1 item 1 1 b item 30 2 item 2 2 item 3 2 item 1 2 b item 30 3 b item 31 3 item 1 3 item 2 3 b item 32
the output i'm looking
item30 item31 item 32 item1 2 1 1 item2 1 1 1 item3 1
i have solution can loop through unique values of each category, there cleaner solution avoids loop entirely?
edit - fixed example missing row. , clarify, category {a,b} relates category item belongs to
you appear doing
with(merge(df[cat=='a',],df[cat=='b',],by='id',all=true), table(droplevels(item.x),droplevels(item.y)))
item 30 item 31 item 32 item 1 2 1 1 item 2 1 1 1 item 3 1 0 0
Comments
Post a Comment