【问题标题】:How to get the object name as a string inside a function in r如何在r中的函数内将对象名称作为字符串获取
【发布时间】:2022-11-19 02:32:50
【问题描述】:

我想用函数更改数据框的列名。

为了用新的列名覆盖我的数据框,我使用了 assign(),它的第一个参数必须是与字符串相同的数据框的名称。为了将名称作为字符串获取,我使用了 deparse(substitute(x)),它在函数外工作。但是在函数内部,它将我的数据框的内容作为字符串而不是名称本身返回...


df <- data.frame(
  emp_id = c (1:5), 
  emp_name = c("Rick","Dan","Michelle","Ryan","Gary"),
  stringsAsFactors = FALSE
)

deparse(substitute(df))

rename_fun <- function(x) {
  colnames(x)[1] <- "___0"
  colnames(x)[2] <- "___1"

  y <- deparse(substitute(x))
  
    assign(y, x, envir = .GlobalEnv)      
}

rename_fun(df)

我也试过

as.character(substitute(x))

但同样的问题...

谢谢你的帮助!

【问题讨论】:

    标签: r function assign


    【解决方案1】:

    我们需要在函数的开头使用deparse

    rename_fun <- function(x) {
     y <- deparse(substitute(x))
      colnames(x)[1] <- "___0"
      colnames(x)[2] <- "___1" 
      
      assign(y, x, envir = .GlobalEnv)      
    }
    

    -测试

    > rename_fun(df)
    > df
      ___0     ___1
    1    1     Rick
    2    2      Dan
    3    3 Michelle
    4    4     Ryan
    5    5     Gary
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用as.character(match.call()$x),它可以在函数中的任何位置使用:

      rename_fun <- function(x) {
        colnames(x)[1] <- "___0"
        colnames(x)[2] <- "___1"
        assign(as.character(match.call()$x), x, envir = .GlobalEnv)      
      }
      

      给予

      rename_fun(df)
      
      df
      #>   ___0     ___1
      #> 1    1     Rick
      #> 2    2      Dan
      #> 3    3 Michelle
      #> 4    4     Ryan
      #> 5    5     Gary
      

      请注意,不建议将对象写入全局环境作为副作用的函数,即使它们正在覆盖现有对象。函数应返回更改后的数据框,然后用户可以选择用于覆盖对象。

      编写函数的更好方法是:

      rename_fun <- function(x) {
        
        colnames(x)[1] <- "___0"
        colnames(x)[2] <- "___1"
        x
      }
      

      哪个会这样称呼:

      df <- rename_fun(df)
      

      并给出相同的结果,同时如果调用者需要,则保留拥有原始数据帧副本的选项。

      创建于 2022-11-18 reprex v2.0.2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-22
        • 1970-01-01
        • 1970-01-01
        • 2021-10-19
        相关资源
        最近更新 更多