【问题标题】:Error: Problem with `mutate()` input x `labels` must be unique错误:`mutate()` 输入问题 x `labels` 必须是唯一的
【发布时间】:2021-08-02 09:15:57
【问题描述】:

我正在尝试以以下方式将一些标记的变量重新编码为 0 到 1 的比例。当我尝试使用c_across() 计算两个变量的平均值时,我得到了这个奇怪的错误Error: Problem with mutate() input market_liberalism. x labels must be unique.

如果我删除值标签,那么它会起作用。我不明白价值标签会导致什么问题。 谢谢。

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

【问题讨论】:

  • 我在执行Recode 步骤时遇到了一些错误。包是否正确。
  • 你试过rowMeansout %&gt;% mutate(market_liberalism = rowMeans(select(., market1:market2)))
  • 我不确定为什么在重新编码步骤会出现错误;但感谢这种变化。

标签: r tidyverse r-haven


【解决方案1】:

对我来说,car::Recode 给出了一个错误,并且不适用于带有 have 标记的类,但 dplyr::recode 如果您加载了 labelled 库,则可以。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2012-11-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 2021-02-13
    相关资源
    最近更新 更多