如何重命名函数内的列?

How to rename column inside the function?

如何使用变量名作为参数重命名手动创建的函数中的列?

例如我的数据是:

df <- data.frame (model = c("A","A","A","B","B","B"),
                  category  = c("z3","f4","c5","d3","g6","B6"),
                  sale = c(1001,1050,-300,-150,-25,960))

现在我想重命名函数内的 'model' 列,并将列名指定为参数

chng <- function(x,var1){
  
  x %>% 
  rename(
    var1 = newname)
}

df2 <- chng(df,"model")

但是这不起作用

我们可能需要扭转它

chng <- function(x,var1){
  
  x %>% 
  rename(
    newname = all_of(var1))
}

-测试

chng(df, "model")
newname category sale
1       A       z3 1001
2       A       f4 1050
3       A       c5 -300
4       B       d3 -150
5       B       g6  -25
6       B       B6  960

另一个选项:

chng <- function(x,var1){
  
  names(x)[match(var1, names(x))] <- 'newname'
  return(x)
}

df2 <- chng(df,"model")
df2

输出:

  newname category sale
1       A       z3 1001
2       A       f4 1050
3       A       c5 -300
4       B       d3 -150
5       B       g6  -25
6       B       B6  960

对于多列

您可以使用以下代码:

chng <- function(x,var1,var2){
  
  names(x)[match(c(var1, var2), names(x))] <- c('newname1', "newname2")
  return(x)
}
chng(df, "model", "category")

输出:

  newname1 newname2 sale
1        A       z3 1001
2        A       f4 1050
3        A       c5 -300
4        B       d3 -150
5        B       g6  -25
6        B       B6  960