-Dataset分割特定の列の値が複数の列に
ID<-c(1,2,3,4,5,6,7)
method<-c("cheque","DD","DD","Cheque","NetBank","NetBank","Cash")
type<-c("Type1","Type1","Type2","Type2","Type3","Type3","Type4")
aid<-c("A1","A1","A2","A2","A3","A3","A4")
month<-c("JAN","JAN","FEB","FEB","MAR","MAR","APR")
year<-c(2016,2016,2015,2015,2017,2017,2018)
Outcome<-c("Positive","Positive","Negative","Negative","Medium","Medium","Neutral")
ser_no<-c("A00001","A00001","A00002","A00002","A00003","A00003","A00004")
Units<-c(100,200,300,400,500,600,700)
amt<-c(1000,1500,2000,3000,4000,2500,6000)
user_cnt<-c(20,20,15,15,32,32,44)
data<-data.frame(ID=ID,type=type,aid=aid,month=month,year=year,Outcome=Outcome,ser_no=ser_no,Units=Units,amt=amt,user_cnt=user_cnt,method=method)
R>データ
ID type aid month year Outcome ser_no Units amt user_cnt method
1 Type1 A1 JAN 2016 Positive A00001 100 1000 20 cheque
2 Type1 A1 JAN 2016 Positive A00001 200 1500 20 DD
3 Type2 A2 FEB 2015 Negative A00002 300 2000 15 DD
4 Type2 A2 FEB 2015 Negative A00002 400 3000 15 Cheque
5 Type3 A3 MAR 2017 Medium A00003 500 4000 32 NetBank
6 Type3 A3 MAR 2017 Medium A00003 600 2500 32 NetBank
7 Type4 A4 APR 2018 Neutral A00004 700 6000 44
Output<-sqldf("select type,aid,month,year,Outcome,ser_no,count(distinct ID) as members,count(type) as entries,sum(UNITS) as UNITS,sum(amt) as amt,
min(amt) as LowestAmt,max(amt) as HighestAmount,AVG(amt) as Mean,user_cnt,cast (count(distinct ID) as real)/user_cnt as Suggestion
from data group by type,aid,month,year,Outcome,ser_no")
R>出力
type aid month year Outcome ser_no members entries UNITS amt LowestAmt HighestAmount Mean user_cnt Suggestion
Type1 A1 JAN 2016 Positive A00001 2 2 300 2500 1000 1500 1250 20 0.10000000
Type2 A2 FEB 2015 Negative A00002 2 2 700 5000 2000 3000 2500 15 0.13333333
Type3 A3 MAR 2017 Medium A00003 2 2 1100 6500 2500 4000 3250 32 0.06250000
Type4 A4 APR 2018 Neutral A00004 1 1 700 6000 6000 6000 6000 44 0.02272727
私はaddメソッド列にしたいですから私の出力にはがあります。
メソッドの列が4つしか値1.Cheque 2.DD 3.NetBank 4.Blankは現金
を表すことができ、私は(最後の4つの列を確認してください)以下の出力方法列の値を追加します。 sqldf
なしでそれを行うことはできますか? グループ内のメソッド値の出現を見つけようとしています。
例:GROUP BY句ごとに、行1は1 Cheque
と1 DD
の値を持ち、したがって、この数は1
と表示されます。 Netbank
とCash
値がカウントあり、したがって存在しない行3は、このようにそこ2 Netbank
値がカウント有するGROUP BY節当たり0。 ある2
として表示されないNetbank
、Cash
とCheque
値がこのようにそこにないようにすると、カウントされた0
type aid month year Outcome ser_no members entries UNITS amt LowestAmt HighestAmount Mean user_cnt Suggestion Cheque DD Netbank Cash
Type1 A1 JAN 2016 Positive A00001 2 2 300 2500 1000 1500 1250 20 0.10000000 1 1 0 0
Type2 A2 FEB 2015 Negative A00002 2 2 700 5000 2000 3000 2500 15 0.13333333 1 1 0 0
Type3 A3 MAR 2017 Medium A00003 2 2 1100 6500 2500 4000 3250 32 0.06250000 0 0 2 0
Type4 A4 APR 2018 Neutral A00004 1 1 700 6000 6000 6000 6000 44 0.02272727 0 0 0 1
追加するのではなく、1つのクエリ自体に期待される出力を得る方法はありますか? **タイプ、援助、月、年、結果、ser_no'の6つの列**をグループ化しています。 'DT [、grp:= paste(データ、タイプ+月+年+結果+補助+ ser_no〜メソッド、fun.aggregate =長さ) ' – Akki
ここで同じコードを使用することができます。 そして、 'dcast(DT [、。=(grp、メソッド)]、grp-メソッド)' – denis