I am trying to select a subset of variables in my dataframe, and rename the variables in the new dataframe. I have a large number of variables that I would need to rename. I am using
dplyr::select
dplyr::select_
Since I have number of variables to rename, I am thinking if I should use a string variable to rename, but not sure if it could be possible? Using a string helps me to manage the newname oldname mapping. Here is an example
dplyr::select
library(dplyr)
library(nycflights13)
set.seed(123)
data <- sample_n(flights, 3)
select(data,yr=year,mon=month,deptime=dep_time)
The question how could I pass the arguments for this in a string, that is the newvariable=oldvariable arguments and then use
dplyr::select_
col_vector <- c("year", "month", "dep_time")
select_(data, .dots = col_vector)
The string I have in mind are:
rename_vector <- c("yr=year","mon=month","deptime=dep_time")
Any suggestions would be very helpful.
colnames(data) <- col_vector
? – Cineramacol_vector
without manually constructing it? Then, you have to provide some logic of how you want to rename these columns. – Cineramanames(mtcars)[c(1, 2, 3)] <- c('z', 'y', 'z')
or using names asnames(mtcars)[names(mtcars) %in% c('x', 'y', 'z')] <- c('mpg', 'cyl', 'disp')
. – Cinerama