简体   繁体   English

R使用分组依据和突变创建自定义函数

[英]R Create Custom Function with Group by and Mutate

I have dataset and performing group_by and mutate functions. 我有数据集并执行group_bymutate函数。

But having errors doing this with custom function and defined column like Value_1 or Value_2 . 但是使用自定义函数和定义的列(例如Value_1Value_2

Pls advise if I might be missing something in the custom function 请告知我自定义函数中是否可能缺少某些内容

Dataset: 数据集:

library(dplyr)

df <- data.frame(
Date = c("2010-10-06", "2010-10-06", "2010-10-06", "2010-10 
06", "2010-10-06", "2010-10-06", "2010-10-06", "2010-10-06"),
Region = c("Central", "Central", "Central", "Central", "North", "North", 
"North", "North"),
Value_1 = c(10, 2, 4, 12, 4, 4, 2, 15),
Value_2 = c(120, 45, 20, 20, 60, 50, 75, 80),
stringsAsFactors = F)

Works Fine: 工作正常:

df %>%
group_by(Date, Region) %>%
mutate(Value_3 = sum(Value_1)) %>%
ungroup()

Error with Custom Function: 自定义功能出错:

test_fn <- function(dataset, Col1) {  
dataset <- dataset %>%
group_by(Date, Region) %>%
mutate(Value_3 =  sum(Col1)) %>%
ungroup()  
return(dataset)
}

df_3 <- test_fn(df, "Value_1")
test_fn <- function(dataset, Col1) {  
  Col1 = sym(Col1)
  dataset <- dataset %>%
    group_by(Date, Region) %>%
    mutate(Value_3 =  sum(!!Col1)) %>%
    ungroup()  
  return(dataset)
}

If you change sym(Col1) to enquo(Col1) then you dont need to pass Col1 as a string, ie test_fn(df, Value_1) 如果将sym(Col1)更改为enquo(Col1)则无需将Col1作为字符串传递,即test_fn(df, Value_1)

Have a look at this for your first half and I or someone will finish the second half of your solution. 看一下您上半部分的内容,我或某人将完成您解决方案的下半部分。 You need to learn about standard vs non-standard evaluation . 您需要了解标准与非标准评估

tfn <- function(data, col, groups) {
  temp <- data %>%
    ## this gets you to group by the variables 
    ## you need to group by in a standard evaluation way
    group_by_(.dots = groups) %>%
    ## now do a mutate with the dynamic variable name
   ## mutate_(.dots and setName(value, var name)

  temp
}

tfn(df, "Value_1", c("Date", "Region"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM