【问题标题】:R: Not able to change column names within a functionR:无法在函数中更改列名
【发布时间】:2016-07-07 17:35:48
【问题描述】:

函数注册。其他执行以下操作: (1) 取一个 26 列的数据框 (2) 将列 1-2 的类更改为因子 (3) 将第 3-26 列的类别更改为数字 (4) 创建第 27 列作为第 3-26 列的总和 (5) 删除除 1 和 27 之外的所有列 (6) 更改第 2 列的列名

  • 如果我正在读取的数据框是 x,我希望第二列名称是 xENRL。

但是当我调用该函数时出现以下错误:

z

    enrollment.other <- function(x){
       x[, 1:2] <- as.data.frame(sapply(x[, 1:2], as.factor))
       x[, 3:26]<- as.data.frame(sapply(x[, 3:26], as.numeric))
       x[, 27] <- rowSums(x[, c(3:26)])
       x <- as.data.frame(x[, c(1, 27)])
       name <- deparse(substitute(x))
       colnames(x)[2] <- sprintf("%sENRL", name)
       as.data.frame(x)
    }

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用match.call

     enrollment.other <- function(x){
        x[1:2] <-  lapply(x[, 1:2], as.factor)
        x[3:26]<-  lapply(x[3:26], as.numeric)
        x[27] <- rowSums(x[3:26])
        x <-   x[c(1, 27)]
        name <- as.character(match.call()[[2]])
        colnames(x)[2] <- sprintf("%sENRL", name)
        x
     }
    
    enrollment.other(d1)
    #   V1 d1ENRL
    #1   3    111
    #2   3    117
    #3   7     98
    #4   5    118
    #5   6    107
    #6   9    109
    #7   3    129
    #8   7    124
    #9   8    107
    #10  3    130
    

    或者如果我们需要使用deparse(substitute

     enrollment.other <- function(x){
       name <- deparse(substitute(x))
       x[1:2] <-  lapply(x[, 1:2], as.factor)
       x[3:26]<-  lapply(x[3:26], as.numeric)
       x[27] <- rowSums(x[3:26])
       x <-   x[c(1, 27)]
       colnames(x)[2] <- sprintf("%sENRL", name)
      x
    }
    

    数据

    set.seed(24)
    d1 <- as.data.frame(matrix(sample(1:9, 10*26, replace=TRUE), ncol=26))
    

    【讨论】:

    • @TariqMusthafa 它返回调用,其中所有参数都由它们的全名指定。因此,在上述情况下,它返回enrollment.other(x=d1)。使用一个简单的例子,f1 &lt;- function(x){ as.list(match.call() ) } f1(d1) 在代码中,我使用了[[2]] 来返回列表元素2。
    • @akrun11 非常感谢!
    猜你喜欢
    • 2020-09-22
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 2021-01-28
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多