【问题标题】:How do I rename a selection of variables using dplyr::rename?如何使用 dplyr::rename 重命名变量选择?
【发布时间】:2018-07-04 21:41:57
【问题描述】:

嗨:我基本上需要将数据框中的一些 likert 项目重新编码为数字,然后重命名它们。我可以在基础 R 中做到这一点,但想知道如何在 tidyverse 中做到这一点。我的刺在这里:

library(tidyverse)
var1<-sample(c('a', 'b', 'c', 'd'))
var2<-var1
var3<-var1
var4<-rnorm(n=4)
df<-data.frame(var1, var2, var3, var4)
recodes<-c('var1', 'var2', 'var3')

df %>% 
select(recodes) %>% 
#everythig works great to this line
mutate_all(funs(dplyr::recode(., 'a'=1, 'b'=0.5, 'c'=0.25, 'd'=0)))%>%
#This is where I need some help
rename_all(funs(paste('ideol', seq(1,3,1))))

解决方案:

df<-df %>% 
select(recodes) %>% 
#everythig works great to this line
mutate_all(funs(dplyr::recode(., 'a'=1, 'b'=0.5, 'c'=0.25, 'd'=0)))%>%
#This is where I need some help
rename_all(funs(paste('ideol', seq(1,3,1), sep='')))%>%
cbind(., df)

【问题讨论】:

  • 如果将 %>% 添加到 mutate_all 行的末尾,则输出为:变量名称为“ideol 1”、“ideol 2”、“ideol 3”的数据帧。这不是想要的结果吗?
  • 您好像忘记了@LucyMLi 提到的管道。
  • 当然。我太马虎了对不起。
  • 已修复,但如何将更改名称的变量存储在原始数据框中?还是将它们添加到原始数据框中?
  • 这对我来说是最后一行。很抱歉弄乱了这个空间cbind(., df)

标签: r dplyr rename tidyverse


【解决方案1】:

转发评论作为答案:

如果在 mutate_all 行末尾添加%&gt;%,则输出为:变量名称为“ideol 1”、“ideol 2”、“ideol 3”的数据框。

【讨论】:

    猜你喜欢
    • 2016-07-30
    • 2021-10-22
    • 1970-01-01
    • 2017-06-10
    • 1970-01-01
    • 2018-09-13
    • 2020-08-30
    • 2021-04-09
    • 2016-01-21
    相关资源
    最近更新 更多