Is there a way "dplyr way" to rename a subset of variables from a data.frame based on variables name translator (vt), a data.frame containing columns with the old and new variable names (old_varname and new_varname respectively). For example:
d <- iris
vt <- data.frame(old_varname=c('Sepal.Length','Petal.Length'),
new_varname=c('a','b'))
d <- d %>% rename_( .... )
#In base R code, this would be:
names(d)[names(d) %in% vt$old_varname] <- vt$std_varname
Edit: Further clarification:
In the dplyr package, we use the rename() function to rename each variable or column name individually. It changes the column names, but the column order is preserved along with DataFrame attributes.
To change multiple columns by name and by index use rename() function of the dplyr package and use setnames() from data.
To rename an object or variable in R, just copy the data. frame variable to another variable by using the assignment operator (<- or =) and remove the existing variable using rm() function.
rename() function in R Language is used to rename the column names of a data frame, based on the older names.
Try this:
d <- iris
vt <- data.frame(old_varname=c('Sepal.Length','Petal.Length'),
new_varname=c('a','b'), stringsAsFactors = F)
d.out <- d %>% rename_(.dots = setNames(vt$old_varname, vt$new_varname))
head(d.out)
a Sepal.Width b 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
Please note that the first argument to setNames
cannot accept factor
, so I modify the vt
by adding stringsAsFactors = F
.
Another way to solve this problem is to unquote a named vector with the new column names as the names and the old column names as the values. Note that I'm using purrr::set_names
to make the named vector.
library(tidyverse)
d <- as_tibble(iris)
vt <- tibble(old_varname=c('Sepal.Length','Petal.Length'),
new_varname=c('a','b'))
d_new_names <- d %>% rename(!!set_names(vt$old_varname, vt$new_varname))
head(d_new_names)
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