简体   繁体   English

如何在dplyr中自动完成列名?

[英]How can I autocomplete column names in dplyr?

I know I can do names(df) to get the columns of a dataframe. 我知道我可以做names(df)来获取数据框的列。 But is there a more convenient way to rename using dplyr in Rstudio? 但是,在Rstudio中,是否有更方便的方法来使用dplyr重命名?

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. dplyr使其变得更加困难,因为我必须知道/键入新旧列名。

I can see certain conversations around autocompletion of column names in dplyr toolchain. 我可以在dplyr工具链中看到有关列名自动完成的某些对话。 But I can't seem to make it work and I have the latest RStudio. 但是我似乎无法使其正常运行,并且我拥有最新的RStudio。

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

You can try something like this (you don't need to use dplyr to transform names automatically). 您可以尝试这样的操作(您无需使用dplyr自动转换名称)。 Just replace the modify_names function with whatever transformation you want to apply to the names. 只需用您想对名称应用的任何转换替换modify_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 . 使用names(*) <- new_value没什么错。 dplyr isn't the be-all and end-all of data manipulation in R. dplyr不是R中数据处理的全部内容。

That said, if you want to include this in a dplyr pipeline, here's how to do it: 就是说,如果您要将其包含在dplyr管道中,请按以下步骤操作:

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. 之所以可行,是因为(几乎)R中的所有内容都是一个函数,特别是分配新名称实际上是对names<-函数的调用。

Recently I had the same question and found this RStudio article: https://support.rstudio.com/hc/en-us/articles/205273297-Code-Completion 最近,我遇到了同样的问题,并发现了以下RStudio文章: 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): 紧随本文之后,要在RStudio中使用dplyr自动完成列名,您必须使用magrittr的%>%运算符(管道):

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. 您可以在文章中找到直观的示例,并在以下位置操纵补全延迟(以减少输入)和其他补全选项:RStudio>工具>全局选项...>代码>补全>补全延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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