根据函数外部的其他变量创建变量

Create variable based on other variable outside function

我想让我的代码通用,我只想更改 YEAR 变量,而不必更改代码中的所有内容

YEAR = 1970

y <- data.frame(col1 = c(1:5))

function (y){
  summarize(column_YEAR = sum(col1))
}
#Right now this gives
  column_YEAR
1          15

#I would like this function to output this (so col1 is changed to column_1970)
  column_1970
1          15

或者例如这个

df <- list("a_YEAR" = anotherdf)
#I would like to have a list with a df with the name a_1970

我试过

df <- list(assign(paste0(a_, YEAR), anotherdf))

但是它不起作用,有人有什么建议吗?提前致谢:)

rlang provides a flexible way to defuse R expressions。您可以使用该功能在 dplyr 流程中创建动态列名。在此示例中,动态列名称是使用 suffix 参数创建的,该参数传递给 dplyr 的摘要上的包装函数。

library("tidyverse")

YEAR = 1970

y <- data.frame(col1 = c(1:5))

function (y) {
  summarize(column_YEAR = sum(col1))
}

my_summarise <- function(.data, suffix, sum_col) {
  var_name <- paste0("column_", suffix)
  
  summarise(.data,
            {{var_name}} := sum({{sum_col}}))
}

my_summarise(.data = y, suffix = YEAR, sum_col = col1)

结果

my_summarise(.data = y, suffix = YEAR, sum_col = col1)
#   column_1970
# 1          15

您也可以直接从全局环境获取参数,但从可读性的角度来看,这是一个较差的解决方案,因为尚不清楚函数如何创建后缀。

my_summarise_two <- function(.data, sum_col) {
    
    var_name <- paste0("column_", YEAR)
    
    summarise(.data,
              {{var_name}} := sum({{sum_col}}))
}

my_summarise_two(.data = y, sum_col = col1)