【问题标题】:"dynamic" naming of column in function函数中列的“动态”命名
【发布时间】:2020-05-28 22:51:18
【问题描述】:

我想分配一个动态名称,即我传递给函数的变量的名称,作为函数正在创建的数据框中的列名。

我试过了

- deparse(substitute(x))
- toString(x)

但没有成功...

代码

a <- (1:3)
b <- (5:7)

df <- data.frame(a,b)

fun <- function(x){
  x %>% mutate(c=a+b)
  colnames(x)[3] <- deparse(substitute(x))
  }

预期行为

运行 fun(df) 后:

  a b  df
1 1 5  6
2 2 6  8
3 3 7 10

改为:

> fun(df)
Error in names(x) <- value : 
  'names' attribute [3] must be the same length as the vector [2]

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以在评估中使用:= (!!)

    fun <- function(x){
        nm1 <-  deparse(substitute(x))
         x %>% 
            mutate(!! nm1 := a+b)
    
       }
    
    fun(df)
    #  a b df
    #1 1 5  6
    #2 2 6  8
    #3 3 7 10
    

    在 OP 的函数中,x %&gt;% mutate 的输出没有被分配回,因此,原始数据集只有两列而不是三列,即如果我们这样做

    fun <- function(x){
       nm1 <- deparse(substitute(x))
        x <- x %>% # assign the output after mutate
                mutate(c=a+b)
       colnames(x)[3] <- nm1
       x # return the dataset
      }   
    
    
    fun(df)
    #  a b df
    #1 1 5  6
    #2 2 6  8
    #3 3 7 10
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-18
      • 2020-05-19
      • 2014-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      相关资源
      最近更新 更多