作者celestialgod (天)
看板R_Language
标题Re: [问题] 资料加总和参照
时间Mon Nov 2 22:13:08 2015
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://webptt.com/cn.aspx?n=bbs/R_Language/M.1446473590.A.F9D.html
1F:推 rubyjay: 这样的话 date为0那个bal就不会加总耶~ 11/02 22:30
改好了
2F:推 rubyjay: 改谢C大,有感觉了,太久没碰,都不知道参数怎麽使用~Tks 11/02 22:36
学姊好,不必客气XDD
※ 编辑: celestialgod (180.218.154.163), 11/02/2015 22:51:43
3F:推 locka: 感觉dplyr真的好强大。学习了!谢谢! 11/02 23:26