推 psinqoo: 好厲害~~ 我想問一下 csv是不是要轉成 data.table 07/03 13:12
推 psinqoo: 計數方式併入 該在哪加語法 07/03 13:49
不太懂csv轉成data.table??
用你能夠讀進R的方法都可以轉吧
計數方法在left_join後面用group_by 去算n()那裏
推 psinqoo: 恩.我想表達是 讀入後先 <-as.data.table() 07/03 15:15
可以不用轉拉,dcast可以直接做data.frame,只是我用fread讀進去就是data.table..
推 psinqoo: 原來如此 07/03 18:01
推 dreamreader: dcast果然簡潔,原po應該是想要count across year 07/04 01:41
我之前沒看清楚,我再補上
# functions for packages
library(reshape2) # dcast
library(data.table) # fread, dcast.data.table
library(dplyr) # summarise, group_by, n, tbl_dt
library(magrittr) # %>%
data_dt = fread("
id year cost
D 2012 120
E 2013 300
F 2014 200
A 2015 155
E 2011 200
F 2014 160
B 2013 165
B 2015 185
C 2012 350
A 2014 310
E 2014 225
F 2015 175") %>% tbl_dt(FALSE)
years = sort(unique(data_dt$year)) %>% as.character
data_dt %>% dcast.data.table(id ~ year, sum, value.var = "cost") %>%
setnames(years, paste0("count_",years)) %>%
left_join(data_dt %>%
dcast.data.table(id ~ year, length, value.var = "cost") %>%
setnames(years, paste0("cost_",years)), "id") %>%
left_join(
data_dt %>% group_by(id) %>%
summarise(total = sum(cost), num = n()), "id")
※ 編輯: celestialgod (123.205.27.107), 07/04/2015 11:58:51
※ 編輯: celestialgod (123.205.27.107), 07/04/2015 11:59:44
推 psinqoo: 感謝 07/07 08:22