看板 R_Language 關於我們 聯絡資訊
dat = data.frame(ID = sample(LETTERS[1:5], 20, TRUE), bal = sample(0:200, 20, TRUE), date = sample(c(0, 2013:2015), 20, TRUE)) # normal method dat2 = subset(dat, dat$date != 0) out = cbind(tapply(dat$bal, dat$ID, sum), tapply(dat2$date, dat2$ID, min)) data.frame(ID = rownames(out), bal = out[,1], date = out[,2]) # ID bal date # A A 232 2013 # B B 55 2013 # C C 868 2013 # D D 346 2013 # E E 470 2013 ## 注意,這裡如果有ID的年份只有0會出錯!! 會在cbind時出現長度不同~~~ ## 這裡或許有人會有更漂亮的解法XD ## 比較好的方式還是透過dplyr吧 # dplyr library(dplyr) dat %>% group_by(ID) %>% summarise(bal = sum(bal), date = min(date[date > 0])) # ID bal date # 1 A 232 2013 # 2 B 55 2013 # 3 C 868 2013 # 4 D 346 2013 # 5 E 470 2013 ※ 引述《rubyjay (佩佩~)》之銘言: : [問題敘述]: : 資料為 : ID bal date : A 10 2015 : A 30 0 : A 100 2014 : B 0 2013 : B 100 0 : . . . : . . . : . . . : 想要整理成: : ID bal date : A 140 2014 : B 100 2013 : . . . : . . . : . . . : 也就是根據同一個ID,bal加總,date取不為0的最小值~ : [程式範例]: : : 因很久沒碰, : 今天先用了 : aggregate(bal~ID,data,sum) : 這樣子可以得到同一個ID,金額(bal)加總,但日期時(date)的部分不知道怎麼處理。 : 有想說不然就先替除date為0的,然後再用aggregate(date~ID,data,min), : 但是因為最後我還是要把他和bal放一起去做分類。 : 大部分參考下列網頁摸索出來的~ : https://stat.ethz.ch/R-manual/R-devel/library/stats/html/aggregate.html : 因為以前大多用R跑模擬,用來分析資料的比較少,原本都用excel, : 只是資料大(10萬筆以上),受不了excel了~(excel常用樞紐和vlookup) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.218.154.163 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1446473590.A.F9D.html
rubyjay: 這樣的話 date為0那個bal就不會加總耶~ 11/02 22:30
改好了
rubyjay: 改謝C大,有感覺了,太久沒碰,都不知道參數怎麼使用~Tks 11/02 22:36
學姊好,不必客氣XDD ※ 編輯: celestialgod (180.218.154.163), 11/02/2015 22:51:43
locka: 感覺dplyr真的好強大。學習了!謝謝! 11/02 23:26