Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enter new column names as string in dplyr's rename function

Tags:

r

dplyr

dplyr's rename functions require the new column name to be passed in as unquoted variable names. However I have a function where the column name is constructed by pasting a string onto an argument passed in and so is a character string.

For example say I had this function

myFunc <- function(df, col){
  new <- paste0(col, '_1')
  out <- dplyr::rename(df, new = old)
  return(out)
}

If I run this

df <- data.frame(a = 1:3, old = 4:6)
myFunc(df, 'x')

I get

  a new
1 1   4
2 2   5
3 3   6

Whereas I want the 'new' column to be the name of the string I constructed ('x_1'), i.e.

  a x_1
1 1   4
2 2   5
3 3   6

Is there anyway of doing this?

like image 331
user1165199 Avatar asked Oct 20 '14 16:10

user1165199


People also ask

How do I change column names in R with dplyr?

To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .

How do I change multiple column names in R?

To change multiple column names by name and by index use rename() function of the dplyr package and to rename by just name use setnames() from data. table . From R base functionality, we have colnames() and names() functions that can be used to rename a data frame column by a single index or name.

How do I rename column names?

To change a column name, enter the following statement in your MySQL shell: ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name; Replace table_name , old_column_name , and new_column_name with your table and column names.


2 Answers

I think this is what you were looking for. It is the use of rename_ as @Henrik suggested, but the argument has an, lets say, interesting, name:

> myFunc <- function(df, col){
+   new <- paste0(col, '_1')
+   out <- dplyr::rename_(df, .dots=setNames(list(col), new))
+   return(out)
+ }
> myFunc(data.frame(x=c(1,2,3)), "x")
  x_1
1   1
2   2
3   3
>

Note the use of setNames to use the value of new as name in the list.

like image 189
kasterma Avatar answered Oct 13 '22 13:10

kasterma


Recent updates to tidyr and dplyr allow you to use the rename_with function.

Say you have a data frame:

library(tidyverse)

df <- tibble(V0 = runif(10), V1 = runif(10), V2 = runif(10), key=letters[1:10])

And you want to change all of the "V" columns. Usually, my reference for columns like this comes from a json file, which in R is a labeled list. e.g.,

colmapping <- c("newcol1", "newcol2", "newcol3")
names(colmapping) <- paste0("V",0:2)

You can then use the following to change the names of df to the strings in the colmapping list:

df <- rename_with(.data = df, .cols = starts_with("V"), .fn = function(x){colmapping[x]})
like image 20
Brian Goodwin Avatar answered Oct 13 '22 14:10

Brian Goodwin