Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dplyr:: rename and select using string variable

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.

like image 865
rajvijay Avatar asked Apr 09 '16 18:04

rajvijay


1 Answers

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"))
like image 57
mpalanco Avatar answered Sep 29 '22 07:09

mpalanco