r - Division of rows based on date in long format -


i have dataframe:

df1 <- data.frame(datum = as.date(c("2015-01-01","2015-02-02","2015-03-03","2015-04-04","2015-05-05",                                     "2015-02-02","2015-04-04","2015-01-01","2015-03-03","2015-05-05")),                    par = c(rep("n",5),rep("p",5)), val = 10:1)          datum par val 1  2015-01-01   n  10 2  2015-02-02   n   9 3  2015-03-03   n   8 4  2015-04-04   n   7 5  2015-05-05   n   6 6  2015-02-02   p   5 7  2015-04-04   p   4 8  2015-01-01   p   3 9  2015-03-03   p   2 10 2015-05-05   p   1 

i want division of rows par = n rows par = p on same date, , add dataframe. expected result should be:

        datum par       val 1  2015-01-01   n 10.000000 2  2015-02-02   n  9.000000 3  2015-03-03   n  8.000000 4  2015-04-04   n  7.000000 5  2015-05-05   n  6.000000 6  2015-02-02   p  5.000000 7  2015-04-04   p  4.000000 8  2015-01-01   p  3.000000 9  2015-03-03   p  2.000000 10 2015-05-05   p  1.000000 11 2015-01-01 n/p  3.333333 12 2015-02-02 n/p  1.800000 13 2015-03-03 n/p  4.000000 14 2015-04-04 n/p  1.750000 15 2015-05-05 n/p  6.000000 

i know can convert wide format (e.g. dcast reshape2), sum columns, , paste them under original df1, seems bit complicated. question is, can done in long format?

using edited dataset, can rbind original dataset dataset created ratio of 'val' other columns grouped 'datum'.

here, using data.table. convert 'data.frame' 'data.table' (setdt(df1)). grouped 'datum' (by = .(datum)), ratio of 'val' corresponding 'n', 'p' elements in 'par'. there missing dates or dates single value, leave row such condition (if(.n>1)) ie. if number of rows in .datum group greater 1, ratio calculation , create 'n/p' 'par' column. after done, can rbind original dataset.

 library(data.table)  setdt(df1)   rbind(df1,df1[, if(.n>1) list(par='n/p',             val=val[par=='n']/val[par=='p'] ), .(datum)]) #         datum par       val # 1: 2015-01-01   n 10.000000 # 2: 2015-02-02   n  9.000000 # 3: 2015-03-03   n  8.000000 # 4: 2015-04-04   n  7.000000 # 5: 2015-05-05   n  6.000000 # 6: 2015-02-02   p  5.000000 # 7: 2015-04-04   p  4.000000 # 8: 2015-01-01   p  3.000000 # 9: 2015-03-03   p  2.000000 #10: 2015-05-05   p  1.000000 #11: 2015-01-01 n/p  3.333333 #12: 2015-02-02 n/p  1.800000 #13: 2015-03-03 n/p  4.000000 #14: 2015-04-04 n/p  1.750000 #15: 2015-05-05 n/p  6.000000 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -