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.
dplyr
Another option using dplyr
in conjunction with setNames
to pass the vector with the new column names:
iris %>%
select(Sepal.Length, Sepal.Width) %>%
setNames(c("sepal_length","sepal_width"))
Base package
setNames(iris[, c("Sepal.Length", "Sepal.Width")],
c("sepal_length", "sepal_width"))
data.table
library(data.table)
setnames(iris, old = c("Sepal.Length", "Sepal.Width"), new = c("sepal_length","sepal_width"))
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