Replacement for "Rename" in Dplyr

Replacement for rename in dplyr

dplyr version 0.3 added a new rename() function that works just like plyr::rename(), but with the old and new names switched:

df <- rename(df, new_name = old_name)

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(.)))))

Rename all columns of dataframe in dplyr without using rename()

No need to rename column by column. You can use set_names, which is equivalent to setNames. Then it is

df <- df %>% 
set_names(nm = c("cluster", "household_number", "respondent_line_number", "date", "num_household_members", location", "education", "marital_status", "age", "weight", "height",
"hemoglobin", "pregnancy_status", "anemia"))

Dplyr: Conditionally rename multiple variables with regex by name

I found a solution using the idea of non standard evaluation from this question and @Maël's answer.

Using map_lgl we create a logical vector that returns TRUE if the column in replace_df_2$old can be found inside the dataframe df. Then we pass this logical vector to replace_df_2$new to get the correct replacement.

df <- mtcars[, 1:5]
df %>%
rename_with(.fn = ~replace_df_2$new[map_lgl(replace_df_2$old,~ any(str_detect(., names(df))))],
.cols = matches(replace_df_2$old))

Result:

                     mpg CYL  disp  hp drat
Mazda RX4 21.0 6 160.0 110 3.90

Error when using dplyr rename_at and stringr str_replace together to rename columns

You need to use the ~ notation when using a custom function.

library(dplyr)

test %>%
dplyr::rename_at(dplyr::vars(starts_with('pre')),
~stringr::str_replace(., pattern = 'pre', replacement ='PRE'))

Also rename_at is now replaced with rename_with.

test %>% 
dplyr::rename_with(~stringr::str_replace(.,pattern = 'pre',replacement ='PRE'),
dplyr::starts_with('pre'))

# A tibble: 2 x 3
# PRE_a PRE_b c
# <dbl> <dbl> <dbl>
#1 1 2 3
#2 4 5 6

Rename() function in R not working with Dplyr pipe inside for loop

Note that you have a data-variable in a function argument (i.e. an env-variable that holds a promise, you need to embrace the argument by surrounding it in doubled braces. This is called [INDIRECTION], which is a glue syntax.

If you want to use the names of variables in the output, you can use glue syntax in conjunction with :=

Therefore you get

rename({{asset}} = price)

Check here for more information

How to rename columns by substituting suffix in R?

library(tidyverse)

eat10.18 %>%
rename_with(~str_replace(.,'_10p$', '_p_10'))

id eat_10 eat_p_10 run_p_10
1 1000 2 1 1
2 1001 4 2 1
3 1002 1 3 2


Related Topics



Leave a reply



Submit