作者celestialgod (天)
看板R_Language
标题Re: [问题] 请问该怎麽写让函式更有弹性?
时间Thu Mar 9 19:26:17 2017
※ 引述《locka (locka)》之铭言:
: [问题叙述]:
: 版上前辈大家晚安~
: 假设我的原始资料栏位有year,month,weekday,y等栏位
: 我想要对他重复做一样的事情
: (根据不同的栏位grouping,计算每组的数量,组内y的平均然後画图)
: 因为差别只在於grouping的栏位不同,所以在想说可不可以用函数包起来
: ex:
: df_group_fn(df,"year","month") >>> 回传以year,month栏位grouping後计算的结果
: df_group_fn(df,"month","weekday") >>> 回传以month,weekday分组後计算的结果
: 也就是只要输入该data frame跟要grouping的栏位
: 就可以直接回传整理好的结果
: 原本想要用dplyr做,大概像下面这样:
: df_group_fn <- function(df,col_1,col_2){
: df %>% group_by(col_1,col_2) %>% summarise(count=n(),avg=mean(y)) %>%
: ggplot(aes(mean,n)+geom_point()
: }
: 不过会卡在指定栏位参数因为是字串的关系, 在group_by那边会有问题
: 所以试着改用data.table的写法:
: df_group_fn <- function(df,col_1,col_2){
: df <- as.data.table(df)
: df[,`:=`(count=.N, avg=mean(y)),by=c(col_1,col_2)]
: ...
: }
: 可是data.table不会像dplyr一样
: 产生只留下grouping跟summarise栏位的dataframe
: 他是在原始的data里面新增栏位,这样我就不知道怎麽画图了...
: 总结我的问题:
: 1. 希望有高手可以指点用dplyr跟data.table把function写得更有弹性的方法
: 2. 如果我今天不想把grouping的栏位数量写死,
: (例如我输入"year"它就只根据year栏位分组,
: 输入"year","month","weekday"就根据那三个栏位分组,该怎麽做呢?
: 3. 最後想问大家实务上会这麽做吗? 很希望可以听到版上大家分享!!
: 先谢谢各位版上先进了 m(_ _)m
: [关键字]:
:
: function, data.table, grouping
:
好读版:
http://pastebin.com/Yxres7jy
我会建议用wrapr去做这件事情
下面先把一般写法列出给原PO参考
library(dplyr)
library(pipeR)
library(ggplot2)
library(data.table)
data("diamonds", package = "ggplot2")
# 一般写法 (dplyr)
df_group_fn <- function(df, meanCol, col_1, col_2){
df %>>% group_by_(.dots = c(col_1, col_2)) %>>%
summarise_(.dots = c(n = "n()",
mean = paste0("mean(", meanCol, ")"))) %>>%
{ggplot(., aes(mean,n)) + geom_point()}
}
df_group_fn(diamonds, "price", "cut", "color")
# 一般写法 (data.table)
dt_group_fn <- function(dt, meanCol, col_1, col_2){
dt[ , .(n = .N, mean = eval(parse(text = paste0("mean(", meanCol, ")")))),
by = c(col_1, col_2)] %>>%
{ggplot(., aes(mean,n)) + geom_point()}
}
dt_group_fn(data.table(diamonds), "price", "cut", "color")
# wrapr + dplyr
library(wrapr)
df_group_fn2 <- function(df, meanCol, col_1, col_2){
let(list(y = meanCol, c1 = col_1, c2 = col_2), {
df %>>% group_by(c1, c2) %>>% summarise(n = n(), mean = mean(y))
}) %>>% {ggplot(., aes(mean,n)) + geom_point()}
}
df_group_fn2(diamonds, "price", "cut", "color")
# wrapr + data.table
dt_group_fn2 <- function(dt, meanCol, col_1, col_2){
let(list(y = meanCol, c1 = col_1, c2 = col_2), {
dt[ , .(n = .N, mean = mean(y)), by = .(c1, c2)]
}) %>>% {ggplot(., aes(mean,n)) + geom_point()}
}
dt_group_fn2(data.table(diamonds), "price", "cut", "color")
# 进阶,不把栏位给死的方法:
# dplyr
df_group_fn3 <- function(df, meanCol, groupByCols){
let(list(y = meanCol), {
df %>>% group_by_(.dots = groupByCols) %>>%
summarise(n = n(), mean = mean(y))
}) %>>%
{ggplot(., aes(mean,n)) + geom_point()}
}
df_group_fn3(diamonds, "price", c("cut", "color"))
# data.table
dt_group_fn3 <- function(dt, meanCol, groupByCols){
let(list(y = meanCol), {
dt[ , .(n = .N, mean = mean(y)), by = groupByCols]
}) %>>% {ggplot(., aes(mean,n)) + geom_point()}
}
dt_group_fn3(data.table(diamonds), "price", c("cut", "color"))
实务上,我自己是做比较接近data engineer的工作
基本上user就会有类似需要,这时候弹性的函数就显得很重要
所以怎麽去利用eval, parse以及...就变得很重要 (没看错就是三个.)
除非全部都是处理data.frame,就可用dplyr透过lazyeval去做
不用wrapr,写起来最漂亮的应该是下面这样: (更正,应该是user用起来最爽XD)
# data.table + ... + substitute
dt_group_fn3 <- function(dt, meanCol, ...){
groupByCols <- as.character(as.list(substitute(list(...)))[-1L])
y <- substitute(meanCol)
dt[ , .(n = .N, mean = mean(y)), by = groupByCols] %>>%
{ggplot(., aes(mean,n)) + geom_point()}
}
dt_group_fn3(data.table(diamonds), price, cut, color)
--
R资料整理套件系列文:
magrittr #1LhSWhpH (R_Language) https://goo.gl/72l1m9
data.table #1LhW7Tvj (R_Language) https://goo.gl/PZa6Ue
dplyr(上.下) #1LhpJCfB,#1Lhw8b-s (R_Language) https://goo.gl/I5xX9b
tidyr #1Liqls1R (R_Language) https://goo.gl/i7yzAz
pipeR #1NXESRm5 (R_Language) https://goo.gl/zRUISx
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 36.235.41.96
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1489058786.A.745.html
1F:推 locka: 先感谢C大详细的说明!第一次看到wrapr,我再研究看看怎麽用 03/09 20:19
2F:→ locka: 说到'...'我常常看到套件里面使用这个参数,藉机请问它的处 03/09 20:20
3F:→ celestialgod: andrew板主有写过一篇 请参考#1LV4sfXT 03/09 20:22
4F:→ locka: 谢谢我有看到了,所以用list处理。那麽substitute跟parse呢? 03/09 20:29
5F:→ locka: 不清楚甚麽时候用eval(parse(text=xx))甚麽时候substitute 03/09 20:31
这个我也不会教XD,去看advanced R吧,看你能学到多少了Orz
6F:推 locka: 不过最後一个做法里面,为什麽price等参数不需要引号啊? 03/09 21:30
7F:→ locka: 哈哈好~我会去找来看 谢谢版主大大~ 03/09 21:32
透过substitute转成symbol / name,所以不需要quote~~
8F:推 ginseng21: 这篇收获良多 03/09 21:37
※ 编辑: celestialgod (36.235.41.96), 03/09/2017 21:49:54
9F:推 locka: 真的!! 03/09 22:28
10F:推 cywhale: 推~~ 03/09 22:43