精華區beta R_Language 關於我們 聯絡資訊
※ 引述《psinqoo (零度空間)》之銘言: : 延伸問題 : 原始資料 : 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 : 想變成這樣子 : ID 12計數 13計數 14計數 15計數 2012金額 2013金額 2014金額 2015金額 總計數 總金額 : A : B : C : D : E : F : 雖然 資料量少 EXCEL 可以計算 : 我想知道R 是否也能用少量語法做到 # 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) data_dt %>% dcast.data.table(id ~ year, sum, value.var = "cost") %>% left_join( data_dt %>% group_by(id) %>% summarise(total = sum(cost), num = n()) ,"id") # id 2011 2012 2013 2014 2015 total num # 1 A 0 0 0 310 155 465 2 # 2 B 0 0 165 0 185 350 2 # 3 C 0 350 0 0 0 350 1 # 4 D 0 120 0 0 0 120 1 # 5 E 200 0 300 225 0 725 3 # 6 F 0 0 0 360 175 535 3 value.var可以不指定,他可以自動選擇,注意要用字串,別跟其他dplyr的function搞混 如果fun.aggregate(第三個input)沒指定就會用length dcast.data.table 是data.table的method,data.frame直接用dcast就好,input是一樣 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.248.28.53 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1435899376.A.3B5.html
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