5

由 dplyr 和 magrittr 等软件包启用的管道隐喻非常有用,并且可以使您的代码在 R 中可读(一项艰巨的任务!)

如何制作一个以将数据框中的所有变量重命名为预定列表而结束的管道?

这是我尝试过的。首先,要测试的简单样本数据:

> library(dplyr)    
> iris %>% head(n=3) %>% select(-Species) %>% t %>% as.data.frame -> test.data
> test.data

               1   2   3
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

这不起作用:

> test.data %>% rename(a=1,b=2,c=3)
Error: Arguments to rename must be unquoted variable names. Arguments a, b, c are not.

我无法通过阅读rename. 我的另一个尝试通过使用花括号来定义代码块来避免错误,但重命名实际上并没有发生:

> test.data %>% { names(.) <- c('a','b','c')}
4

3 回答 3

5

'1','2','3'你是正确的,除了使用 setNames {stats} 而不是重命名(zx8754 在我之前的评论中回答)

setNames:这是一个方便的函数,用于设置对象的名称并返回该对象。它在函数定义的末尾最有用,在该函数定义中创建要返回的对象,并且不希望将其存储在名称下,以便可以分配名称。

您的示例(关闭只需使用 setNames 更改重命名)

iris %>% 
   head(n=3) %>% 
   select(-Species) %>% 
   t %>% 
   as.data.frame %>% 
   rename(a=1,b=2,c=3)

回答

iris %>% 
   head(n=3) %>% 
   select(-Species) %>%
   t %>%
   as.data.frame %>%
   setNames(c('1','2','3'))

另一个例子

name_list <- c('1','2','3')

iris %>% 
   head(n=3) %>% 
   select(-Species) %>%
   t %>%
   as.data.frame %>%
   setNames(name_list)
于 2016-02-26T18:05:59.697 回答
2

我们可以dplyr::rename通过用反引号(`)括起来重命名数字变量名称。

library(dplyr)

iris %>% 
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  dplyr::rename(a=`1`, b=`2`, c=`3`)
# a   b   c
# Sepal.Length 5.1 4.9 4.7
# Sepal.Width  3.5 3.0 3.2
# Petal.Length 1.4 1.4 1.3
# Petal.Width  0.2 0.2 0.2

作为另一种方式,我们可以使用stats::setNames, magrittr::set_names和来设置列名purrr::set_names

library(dplyr)
library(magrittr)
library(purrr)

iris %>% 
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  stats::setNames(c("a", "b", "c"))

iris %>% 
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  magrittr::set_names(c("a", "b", "c"))

iris %>% 
  head(n=3) %>% select(-Species) %>% t %>% as.data.frame %>%
  purrr::set_names(c("a", "b", "c"))
# The results of above all codes is as follows:
# a   b   c
# Sepal.Length 5.1 4.9 4.7
# Sepal.Width  3.5 3.0 3.2
# Petal.Length 1.4 1.4 1.3
# Petal.Width  0.2 0.2 0.2
于 2016-10-27T08:09:54.987 回答
2

我得到这个工作的方式,我需要来自 magrittr 包的 tee 运算符:

> library(magrittr)
> test.data %T>% { names(.) <- c('a','b','c')} -> renamed.test.data
> renamed.test.data
               a   b   c
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

请注意,对于具有普通(即不是数字)变量名称的数据框,您可以这样做:

> # Rename it with rename in a normal pipe
> renamed.test.data %>% rename(x=a,y=b,z=c) -> renamed.again.test.data
> renamed.again.test.data
               x   y   z
Sepal.Length 5.1 4.9 4.7
Sepal.Width  3.5 3.0 3.2
Petal.Length 1.4 1.4 1.3
Petal.Width  0.2 0.2 0.2

不过,上面的技巧(编辑:或者更好的是,使用 setNames)仍然很有用,因为有时您已经在字符向量中拥有名称列表,而您只想一次设置它们而不用担心写出每个替换一对。

于 2016-02-26T16:09:46.850 回答