spindoctor
spindoctor

Reputation: 1895

How do I rename a selection of variables using dplyr::rename?

Hi: I basically need to recode some likert items in a dataframe to numeric and then rename them. I can do this in base R but would like to know how to do this in tidyverse. My stab is here:

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))))

Solution:

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)

Upvotes: 0

Views: 148

Answers (1)

LucyMLi
LucyMLi

Reputation: 657

Reposting comment as answer:

If you add %>% to the end of the mutate_all line, the output is: a data frame with variable names "ideol 1", "ideol 2", "ideol 3".

Upvotes: 1

Related Questions