dataframe - Transposing two fields to one unique key in R -
i have dataframe has productid, seller1name, seller1price, seller2name, seller2price below. table (df) unique productid:
productid seller1name seller1price seller2name seller2price 1 $1 x $3 2 b $3 y $6 3 c $2 z $1
the desired output should df:
productid seller price 1 $1 1 x $3 2 b $3 2 y $6 3 c $2 3 z $1
i tried using reshape package results funky:
output <-melt(df, id = c("productid"))
is there better way this?
in data.table v1.9.5
, current devel version, melt
data.tables has gained new feature -- able melt on multiple columns..
require(data.table) ## v1.9.5+ ans = melt(setdt(df), measure=patterns("name$", "price$"), value.name=c("seller", "price"))
we provide columns grouped while melting list in measure.vars
argument.
now, can remove variable
column , reorder follows:
setorder(ans[, variable := null], productid)[] # productid seller price # 1: 1 $1 # 2: 1 x $3 # 3: 2 b $3 # 4: 2 y $6 # 5: 3 c $2 # 6: 3 z $1
hth
Comments
Post a Comment