由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')}
rename(a='1', b='2', c='3')
可以工作。 - Pierre L