Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding error when using rename in dplyr and column doesn't exist

Tags:

r

dplyr

Is there a clever way to use the rename function in dplyr when in some instances the column to be renamed doesn't exist?

For example, I would like the following not to result in an error

mtcars%>%rename(miles_per_gallon=mpg,missing_varible=foo) 

(results in this: Error: Unknown variables: foo.)

but rather the dataframe with all possible renaming done.

Currently I am explicitly checking that the specific column exists before renaming

Thanks

Iain

like image 415
Iain Avatar asked Dec 14 '15 20:12

Iain


People also ask

How do I rename a column in dplyr in R?

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

What does rename () do in R?

rename() function in R Language is used to rename the column names of a data frame, based on the older names.

How do I rename multiple columns in dplyr?

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 a column in R using Colnames?

Method 1: using colnames() method colnames() method in R is used to rename and replace the column names of the data frame in R. The columns of the data frame can be renamed by specifying the new column names as a vector. The new name replaces the corresponding old name of the column in the data frame.


1 Answers

Perhaps not the intention of the designers, but you can utilize the scoped verb rename_all and the dplyr function recode, which takes one or more key value pairs like old_name = "New Name".

library(dplyr)  rename_all(iris, recode, Sepal.Length = "sepal_length", cyl = "cylinder") #     sepal_length Sepal.Width Petal.Length Petal.Width    Species # 1            5.1         3.5          1.4         0.2     setosa # 2            4.9         3.0          1.4         0.2     setosa # 3            4.7         3.2          1.3         0.2     setosa # 4            4.6         3.1          1.5         0.2     setosa # 5            5.0         3.6          1.4         0.2     setosa # 6            5.4         3.9          1.7         0.4     setosa # 7            4.6         3.4          1.4         0.3     setosa # 8            5.0         3.4          1.5         0.2     setosa # 9            4.4         2.9          1.4         0.2     setosa 
like image 133
Tyler Hays Avatar answered Oct 26 '22 05:10

Tyler Hays