【问题标题】:Analysing Multiple Choice Values in R - Getting Frequency count of Variables分析 R 中的多项选择值 - 获取变量的频率计数
【发布时间】:2018-10-16 16:21:35
【问题描述】:

我导入了以下数据,其中一个问题的结构如下:

问题 a) Type_of_input [MULTIPLE SELECT]

  1. 1:肥料
  2. 2:农药
  3. 3:除草剂
  4. 4:喷雾器

问题 b) 总量。

在 data.frame 中,数据被拆分为一个矩阵,每个选项位于单独的列中,观察值为 0 和 1。如果选择了该选项,则为 1,如果未选择该选项,则为 0。请参阅下面的 data.frame 模型。

Type_of_input <- c("1:Fertiliser|2:Pesticide|4:Sprayer", "2:Pesticide|3:Herbicides", "2:Pesticide|3:Herbicide|4:Sprayer")
Fertiliser <- c(1,0,0)
Pesticide <- c(1,1,1)
Herbicide <- c(0,1,1)
Sprayer <- c(1,0,1)
total_volume <- c(40,50,60)
df_inputs <- data.frame(Type_of_input, Fertiliser, Pesticide, Herbicide, Sprayer, volume)

df_inputs

                       Type_of_input Fertiliser Pesticide Herbicide Sprayer total_volume
1 1:Fertiliser|2:Pesticide|4:Sprayer          1         1         0       1           40
2           2:Pesticide|3:Herbicides          0         1         1       0           50
3  2:Pesticide|3:Herbicide|4:Sprayer          0         1         1       1           60

如何获取每个输入的频率表计数及其total_volume

【问题讨论】:

    标签: r dplyr frequency data-analysis


    【解决方案1】:

    这是一种解决方案,您可以在其中计算每一列感兴趣的总和

    Type_of_input <- c("1:Fertiliser|2:Pesticide|4:Sprayer", "2:Pesticide|3:Herbicides", "2:Pesticide|3:Herbicide|4:Sprayer")
    Fertiliser <- c(1,0,0)
    Pesticide <- c(1,1,1)
    Herbicide <- c(0,1,1)
    Sprayer <- c(1,0,1)
    df_inputs <- data.frame(Type_of_input, Fertiliser, Pesticide, Herbicide, Sprayer)
    
    library(dplyr)
    
    df_inputs %>%
      select(-Type_of_input) %>%
      summarise_all(sum)
    
    #    Fertiliser Pesticide Herbicide Sprayer
    # 1          1         3         2       2
    

    你可以有这样的不同格式

    library(tidyverse)
    
    df_inputs %>%
      select(-Type_of_input) %>%
      summarise_all(sum) %>%
      gather(var, value) %>%
      arrange(desc(value))
    
    #          var value
    # 1  Pesticide     3
    # 2  Herbicide     2
    # 3    Sprayer     2
    # 4 Fertiliser     1
    

    如果您想使用 value 变量来排列您的数据集并在顶部放置最流行的值。

    【讨论】:

    • 我该如何总结,如果在这个数据框的末尾有另一个新列,例如total_volume &lt;- c(40,50,60) 我想在给定一个新的数字列的情况下捕获摘要
    • 你能编辑你的问题并展示你想要的输出吗?
    • 我的理想输出是散点图。我想了解每个Type_of_input 与我介绍的另一个名为Total_volume 的列之间的关系。在上面的例子中,我如何使用Pesticide的值3.来创建一个散点图,显示农药与数字列total_volume中的值之间的关系
    【解决方案2】:

    你只需这样做:

    sapply(df_inputs[-1],sum)
    

    【讨论】:

      猜你喜欢
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2020-07-01
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多