maximusdooku
maximusdooku

Reputation: 5542

How can I autocomplete column names in dplyr?

I know I can do names(df) to get the columns of a dataframe. But is there a more convenient way to rename using dplyr in Rstudio?

Earlier:

names(df)=c("anew","bnew","cnew")

Now?:

library(dplyr)
rename(df, aold = anew, bold = bnew, cold= cnew)

dplyr makes it more difficult as I have to know/type both the old and new column names.

I can see certain conversations around autocompletion of column names in dplyr toolchain. But I can't seem to make it work and I have the latest RStudio.

https://plus.google.com/+SharonMachlis/posts/FHknZcbAdLE

Upvotes: 0

Views: 1242

Answers (3)

CamiloEr
CamiloEr

Reputation: 1222

Recently I had the same question and found this RStudio article: https://support.rstudio.com/hc/en-us/articles/205273297-Code-Completion

Following the article, to autocomplete column names with dplyr in RStudio you have to use the magrittr’s %>% operator (pipelines):

library(dplyr)
df %>% rename(aold = anew, bold = bnew, cold= cnew) #Select the variable (old) name after typing the initials (3) + tab

You can find the visual example in the article and manipulate the completation delay (to type less) and other completation options in: RStudio>Tools>Global options...>Code>Completation>Completation delay.

Upvotes: 0

Hong Ooi
Hong Ooi

Reputation: 57696

There's nothing wrong with using names(*) <- new_value. dplyr isn't the be-all and end-all of data manipulation in R.

That said, if you want to include this in a dplyr pipeline, here's how to do it:

df %>% `names<-`(c("a_new", "b_new", "c_new"))

This works because (almost) everything in R is a function, and in particular assigning new names is really a call to the names<- function.

Upvotes: 0

Jessica Su
Jessica Su

Reputation: 41

You can try something like this (you don't need to use dplyr to transform names automatically). Just replace the modify_names function with whatever transformation you want to apply to the names.

> modify_names <- function(any_string) {
+    return(paste0(any_string, "-new"))
+ }
>


> df <- data.frame(c(0, 1, 2), c(3, 4, 5))
> names(df) <- c("a", "b")
> df
  a b
1 0 3
2 1 4
3 2 5


> names(df) <- modify_names(names(df))
> df
  a-new b-new
1     0     3
2     1     4
3     2     5

Upvotes: 2

Related Questions