【问题标题】:Survey data in R: frequencies of responses not selectedR 中的调查数据:未选择的响应频率
【发布时间】:2021-06-04 20:33:56
【问题描述】:

我想知道在 R 中清理调查数据时是否有人可以解决以下问题。

假设一项调查有 Q1“你的性别是什么”:男性、女性、不想说。调查中没有人选择“Prefer not to say”,所以我跑频率的时候只看到:

Q1 男:8,女:8。

有没有办法将“不想说”中的代码写入 Q1,这样当我运行频率时,我会看到:

Q1 Male : 8, Female: 8, Prefer not to say: 0.

这是一些示例数据和代码:

 dat_in<-read_table2("ID    Gender
1   1
2   1
3   1
4   1
5   1
6   2
7   2
8   2
9   2
10  2
11  2
12  2
13  1
14  2
15  1
16  2
")
    
data_cat <- dat_in %>% mutate_if(is.numeric,as.character) %>% mutate(across(matches("Gender"), ~fct_recode(., "Female" = "1","Male"="2")))

lapply(select_if(data_cat, is.factor),
       function(x) {
           df = data.frame(table(x))
           return(df)
       })

【问题讨论】:

    标签: r survey


    【解决方案1】:

    将其更改为factor,并指定levels,这样即使没有元素,它也会返回频率计数为0

    table(factor(dat_in$Gender, levels = c("Male", "Female", "Prefer not to say")))
    

    -输出

                  Male            Female Prefer not to say 
                    8                 8                 0 
    

    如果有很多变量,即字符/因子类,循环列,添加“不想说”作为新级别

    i1 <- sapply(dat_in, function(x) is.character(x)|is.factor(x))
    dat_in[i1] <- lapply(dat_in[i1], function(x) {
                 if(is.factor(x)) {
                   levels(x) <- c(levels(x), "Prefer not to say")
                  } else {
                    x <- factor(x, levels = c(unique(x), "Prefer not to say"))
                }
               x })
    

    或者如果我们使用tidyverse,那么这可以使用来自forcatsfct_expand来完成

    library(dplyr)
    library(forcats)
    dat_in <- dat_in %>%
               mutate(across(where(~ is.factor(.)|is.character(.)), ~ 
                   fct_expand(., "Prefer not to say")))
    

    【讨论】:

    • 谢谢!我的调查数据中有很多变量,您是否可以重复使用我的代码/模板来添加“不想说”作为一个级别? fct_recode 可以吗?
    • @NewBee 你仍然可以使用base R。查找类字符/因子 ('i1') 的列。循环遍历这些并更改levels,如果它是通过添加新级别的因素,如果它是字符,则转换为factor,级别指定为该列的唯一值,新值'不想说'跨度>
    • @NewBee 更新为 fct_expand 希望它对你有用
    • 再次感谢——当我使用 tidyverse 选项并运行表循环时,我得到了一个命名列表,而不是预期的输出
    猜你喜欢
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2017-12-17
    • 2020-06-30
    相关资源
    最近更新 更多