简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM