r - Collapse columns before aggregating by count -



r - Collapse columns before aggregating by count -

i have imagine simple question, cannot figure out after deal of board searching/reading tutorials.

i have df name entries in columns 5 through 12 of 1 type. name strings (see below example). utilize aggregate or ddply (or another, if easier...) function collapse columns , homecoming count of each unique entry.

id | name 1 | name 2 | name 3 row 1: 278 | john | tim | mike row 2: 279 | tim | steve | john row 3: 280 | tim | doug | dave

so ideally i'd get:

tim | 3 john | 2 mike | 1 etc. | 1

i know how works 1 column:

counts=aggregate(numeric(nrow(df)), df[c(4)], length)

but when utilize similar line multiple columns, returns unique combinations of 7 columns, instead of nx2 vector aggregated unique entries , total sums.

counts2=aggregate(numeric(nrow(df)),df[c(5:12)],fun = function(x) length(unique(x)))

thank much help.

i'm not speed on new packages hadley has come with, here's how i'd solve problem using reshape2 package. thought (same above) collapse columns 1 column , summarize data:

library(reshape2) dcast(data = melt(foo, id.vars = "id"), value ~ .) #--- value . 1 dave 1 2 doug 1 3 john 2 4 mike 1 5 steve 1 6 tim 3

r aggregate plyr

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -