I am trying to recode some labelled variables to a 0 to 1 scale in the following fashion. When I try to calculate the mean of the two variables using c_across()
I get this odd error Error: Problem with mutate() input market_liberalism. x labels must be unique.
If I delete the value labels then it works. I don't understand what problem the value labels cause. Thank you.
#Install car package if necessary
#install.packages('car')
library(tidyverse)
library(car)
structure(list(PESE15 = structure(c(3, 5, 5, 8, NA), label = "The Government Should Leave it Entirely to the Private Sector to Create Jobs", na_values = c(8, 9), format.spss = "F1.0", display_width = 0L, labels = c(`Strongly agree` = 1, `Somewhat agree` = 3, Somewhatdisagree = 5, Stronglydisagree = 7,D.K. = 8, Refused = 9), class = c("haven_labelled_spss", "haven_labelled", "vctrs_vctr", "double")), MBSA2 = structure(c(3, 8, 1, 1, NA), label = "People Who Do Not Get Ahead Should Blame Themselves Not the System", na_values = 8, format.spss = "F1.0", display_width = 0L, labels = c(`Strongly agree` = 1, Agree = 2, Disagree = 3, Stronglydisagree = 4, `No opinion` = 8), class = c("haven_labelled_spss", "haven_labelled", "vctrs_vctr", "double"))), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"), label = "NSDstat generated file")->out
#use the car::Recode command to convert values to 0 to 1
out$market1<-Recode(out$PESE15, "1=1; 3=0.75; 5=0.25; 7=0; 8=0.5; else=NA")
out$market2<-Recode(out$MBSA2, "1=1; 2=0.75; 3=0.25; 4=0; 8=0.5; else=NA")
#Use dplyr to try to calculate the average
out %>%
rowwise() %>%
mutate(market_liberalism=mean(
c_across(market1:market2))) -> out2
#setting value labels to NULL makes it work.
val_labels(out$market1)<-NULL
val_labels(out$market2)<-NULL
out %>%
rowwise() %>%
mutate(market_liberalism=mean(
c_across(market1:market2)))
For me car::Recode
gives an error and does not work with haven labelled class but dplyr::recode
does if you have labelled
library loaded.
library(labelled)
library(dplyr)
out %>%
mutate(PESE15 = recode(PESE15, `1` = 1,`3` = 0.75, `5`=0.25, `7`=0, `8` = 0.5),
MBSA2 = recode(MBSA2, `1`=1, `2`=0.75, `3`=0.25, `4`=0, `8`=0.5),
market_liberalism = rowMeans(., na.rm = TRUE))