【问题标题】:How to turn multiple dummy vars into 1 factor variable?如何将多个虚拟变量转换为 1 个因子变量?
【发布时间】:2018-03-30 12:13:58
【问题描述】:

我有一个来自调查的庞大数据集,其中包含大量虚拟变量。每个虚拟变量都是具有“引用”和“未引用”级别的因子。由于不同的语句组属于同一个主题,我想将它们转换为 1 个更大的因子变量,它将虚拟变量作为级别,并且值保持“引用”和“未引用”(或 1 和 0,不目前的事情)。

所以我现在从 2 个虚拟变量看起来像这样:

    pp_plan_thoughtAWhile   pp_plan_justHappen  
     not quoted                  not quoted 
     not quoted                  not quoted 
     not quoted                  not quoted 
     not quoted                  not quoted 
     not quoted                  quoted 
     quoted                      quoted 

我需要它看起来像这样:

               #plan 
      ## value     thoughtAWhile    justHappen
           0           350             550  
           1           650             450

有人知道怎么做吗?任何帮助将不胜感激,我正在努力!

【问题讨论】:

  • 右边是0和1的频率对吧?
  • @RanaUsman 这里的右手边是什么意思?
  • 350、650、550 450。
  • @RanaUsman 哦,是的,当然!对不起,没意识到:)

标签: r dummy-variable


【解决方案1】:

我们可以使用gather 将数据集重塑为“长”格式,然后使用countspread 将频率转换为“宽”格式

library(tidyverse)
gather(df1) %>%
   count(key, value) %>%
   spread(key, n)

【讨论】:

  • 我在计数时尝试了这个,它抛出了这个错误:.fun(.value[i], ...) 中的错误:参数的“类型”(字符)无效
  • @DanaDaskalova 您使用的是dplyr::count 还是该函数被其他库屏蔽了。试试gather(df1) %>% dplyr::count(key,value)
【解决方案2】:

这是执行此操作的一种方法。

数据

   pp_plan_thoughtAWhile <-  sample(c("Quoted", "NotQuoted"), 10, replace = T, prob=c(0.7, 0.3))
   pp_plan_justHappen  <- sample(c("Quoted", "NotQuoted"), 10, replace = T, prob=c(0.5, 0.5))
   dv <- data.frame(pp_plan_justHappen, pp_plan_thoughtAWhile)

一些处理

dv$pp_plan_justHappen <- as.factor (dv$pp_plan_justHappen) 
dv$pp_plan_thoughtAWhile <- as.factor(dv$pp_plan_thoughtAWhile)

library(reshape2)
mdata <- melt(dv)

mdata$bin_plan_justhappen <- ifelse(mdata$pp_plan_justHappen=="Quoted", 1, 0)
mdata$bin_plan_thoughtwhile <- ifelse(mdata$pp_plan_thoughtAWhile=="Quoted", 1, 0)
library(plyr)
table(mdata$bin_plan_justhappen, mdata$bin_plan_thoughtwhile)
plyr::count(mdata, c("bin_plan_justhappen", "bin_plan_thoughtwhile"))

结果

bin_plan_justhappen bin_plan_thoughtwhile freq
               0                     1    2
               1                     0    1
               1                     1    7

【讨论】:

  • 谢谢你,但我不知道确切的概率,我给出的例子中的那些仅供参考,所以我不知道这会如何工作
  • 我刚刚根据您的示例生成了随机数据以完成实施。您不需要生成数据,它应该已经扩展到您的问题。
猜你喜欢
  • 1970-01-01
  • 2018-03-22
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
相关资源
最近更新 更多