Dav*_*man 5 r rename dplyr magrittr
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
Run Code Online (Sandbox Code Playgroud)
这不起作用:
> test.data %>% rename(a=1,b=2,c=3)
Error: Arguments to rename must be unquoted variable names. Arguments a, b, c are not.
Run Code Online (Sandbox Code Playgroud)
我无法通过阅读rename
. 我的另一个尝试通过使用花括号定义代码块来避免错误,但重命名实际上并没有发生:
> test.data %>% { names(.) <- c('a','b','c')}
Run Code Online (Sandbox Code Playgroud)
'1','2','3'你是正确的,除了使用 setNames {stats} 而不是 rename (zx8754 在我之前的评论中回答)
setNames:这是一个方便的函数,用于设置对象的名称并返回该对象。它在函数定义的末尾最有用,在该定义中创建要返回的对象并且不希望将其存储在名称下,以便可以分配名称。
您的示例(关闭只需使用 setNames 更改重命名)
iris %>%
head(n=3) %>%
select(-Species) %>%
t %>%
as.data.frame %>%
rename(a=1,b=2,c=3)
Run Code Online (Sandbox Code Playgroud)
回答
iris %>%
head(n=3) %>%
select(-Species) %>%
t %>%
as.data.frame %>%
setNames(c('1','2','3'))
Run Code Online (Sandbox Code Playgroud)
另一个例子
name_list <- c('1','2','3')
iris %>%
head(n=3) %>%
select(-Species) %>%
t %>%
as.data.frame %>%
setNames(name_list)
Run Code Online (Sandbox Code Playgroud)
为了让它工作,我需要 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
Run Code Online (Sandbox Code Playgroud)
请注意,对于具有正常(即不是数字)变量名称的数据框,您可以执行以下操作:
> # 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
Run Code Online (Sandbox Code Playgroud)
不过,上面的技巧(编辑:或者更好的是,使用 setNames)仍然有用,因为有时您已经在字符向量中拥有名称列表,并且您只想一次设置它们,而不必担心写出每个替换一对。