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
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) .
rename() function in R Language is used to rename the column names of a data frame, based on the older names.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With