Home > Blockchain >  How to rename column inside the function?
How to rename column inside the function?

Time:05-25

How to rename column inside the manually created function using variable name as an argument?

for instance my data is:

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))

Now I want to rename 'model' column inside the function and I specify column name as an argument

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

df2 <- chng(df,"model")

However this does not work

CodePudding user response:

We may need to reverse it

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

-testing

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

CodePudding user response:

Another option:

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

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

Output:

  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
  • Related