Enter new column names as string in dplyr's rename function
I think this is what you were looking for. It is the use of rename_
as @Henrik suggested, but the argument has an, lets say, interesting, name:
> myFunc <- function(df, col){
+ new <- paste0(col, '_1')
+ out <- dplyr::rename_(df, .dots=setNames(list(col), new))
+ return(out)
+ }
> myFunc(data.frame(x=c(1,2,3)), "x")
x_1
1 1
2 2
3 3
>
Note the use of setNames
to use the value of new as name in the list.
How to rename selected columns using dplyr with new column names as strings
If you want to use dplyr's rename
function, it would be best to create a named vector / list and call it using the .dots
argument in the standard evaluation version:
cols <- c("Sepal.Length", "Petal.Length")
to_app <- ".xxx"
cols <- setNames(cols, paste0(cols, to_app))
df %>% rename_(.dots = cols)
## A tibble: 5 × 3
# Sepal.Length.xxx Sepal.Width Petal.Length.xxx
#* <dbl> <dbl> <dbl>
#1 5.1 3.5 1.4
#2 4.9 3.0 1.4
#3 4.7 3.2 1.3
#4 4.6 3.1 1.5
#5 5.0 3.6 1.4
Note however, that this approach is subject to change with the next version 0.6.0 of dplyr (see e.g. http://blog.rstudio.org/2017/04/13/dplyr-0-6-0-coming-soon/ and http://dplyr.tidyverse.org/articles/programming.html).
R dplyr: rename variables using string functions
I think you're looking at the documentation for plyr::rename
, not dplyr::rename
. You would do something like this with dplyr::rename
:
iris %>% rename_(.dots=setNames(names(.), tolower(gsub("\\.", "_", names(.)))))
Using glue in new column name in rename() in R
The following is also possible, without explicit use of glue
, but with the walrus operator :=
, like in @Ronak Shah's answer:
df %>% rename("Change since {date_variable}" := change)
Pass character string of column names (e.g. c(speed, dist ) to `across` function in R
You can't use substitute()
or eval()
on character vectors. You need to parse those character vectors into language objects. Otherwise when you eval a string, you just get that string back. It's not like eval
in other languages. One way to do the parsing is str2lang
. Then you can inject that expression into the across
using tidy evaulation's !!
. For example
mtcars_2 %>%
mutate(across(.cols = !!str2lang(.$cols_to_modify),.fns = round))
Parsing string as column name in dplyr
I would use a named vector instead of trying to mess around with the dplyr programming nuances. A benefit is that this method is already vectorized.
rename_cols <- function(col) {
name = paste0(col, "_new") #I want to be able to parse this into the rename function below
mtcars %>%
rename(setNames(col, name))
}
rename_cols(colnames(mtcars))
# mpg_new cyl_new disp_new hp_new drat_new wt_new qsec_new vs_new am_new gear_new carb_new
# Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
# Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
# Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
# Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
# Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
# Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
# ...
Edit
In this case, you might also find rename_with()
to be what you need.
library(dplyr)
colnames(mtcars) -> cols
mtcars %>%
rename_with(~ paste0(., "_new"), any_of(cols))
# which is the same as the more concise but maybe less clear...
mtcars %>%
rename_with(paste0, any_of(cols), "_new")
Rename all column names that include a certain string
You can use rename_with
-
library(dplyr)
library(stringr)
da %>% rename_with(~str_replace(., 'likes_comment', 'number_likes'))
# number_likes_1 number_likes_2 number_likes_3 quotes_comment1
#1 1 2 5 2
#2 2 2 2 1
#3 3 3 3 3
#4 4 1 1 4
# quotes_comment2_ quotes_comment3
#1 3 2
#2 5 3
#3 7 1
#4 1 2
How to use rename_with() in pipe to change all column names from vector
It doesn't seem like rename_with
is the right function for this. I guess you could do
iris %>%
rename_with(~newcolnames)
as kind of a hack. You can also use rename
iris %>%
rename(!!!setNames(names(.), newcolnames))
But the setNames
method just seems much more apt.
Applying dplyr's rename to all columns while using pipe operator
I know this is an old question, and I'm sure you found the solution by now, but I stumbled here searching for the same question, and ultimately found a few new ways to do this.
Dplyr
Using dplyr 0.6.0
and above, there is now a rename_all
function:
dta %>%
rename_all(funs(gsub("[[:punct:]]", "", make.names(names(dta)))))
Which works, but it's a little messy to me. If you want more flexibility with dplyr
, you can also call on:
rename_at
rename_if
Janitor
This is a pretty nice package (with plenty of additional utility) that can easily clean up column names:
library(janitor)
dta %>%
clean_names()
Which will rename and clean all column names to the following:
[1] "this_is_column_one" "another_amazing_column_name" "x_this_columns_is_so_special"
Everything becomes snake_case rather than CamelCase, but overall clean_names
is very flexible in the column names it handles. If that IS a deal breaker, you can use yet another package snakecase
for its function to_big_camel_case()
within the rename_all
function...although that is starting to get a little too esoteric
How to replace column names that include specific string r
We can use rename_at
library(dplyr)
df1 <- df1 %>%
rename_at(vars(ends_with('score')), ~ replace.cols)
df1
# a b c_score a_score
#1 1 5 10 1
#2 2 6 10 3
#3 3 7 2 5
#4 4 8 3 6
#5 5 9 4 7
or with str_remove
library(stringr)
df1 %>%
rename_at(vars(ends_with('score')), ~ str_remove(., '\\.\\d+'))
Or using base R
(assuming the column names order is maintained in 'replace.cols')
names(df1)[endsWith(names(df1), 'score')] <- replace.cols
Related Topics
Extracting Value Based on Another Column
Arrange N Ggplots into Lower Triangle Matrix Shape
How to Add a Prefix to Several Variable Names Using Dplyr
In R, Use Lubridate to Convert Hms Objects into Seconds
Explanation of R: Options(Expressions=) to Non-Computer Scientists
Regular Analysis Over Irregular Time Series
How to Make My Axis Ticks Face Inwards in Ggplot2
Can't Load X11 in R After Os X Yosemite Upgrade
Replace All Na with False in Selected Columns in R
How to Build a Graph from a Data Frame Using the Igraph Package
How to Remove Columns with Same Value in R
How to Display the Median Value in a Boxplot in Ggplot
Large Matrices in R: Long Vectors Not Supported Yet
Grouped Barplot with Cut Y Axis
Justification of Multiple Legends in Ggmap/Ggplot2