【问题标题】:How do I bin a variable across a number of observations for each specimen?如何在每个样本的多个观察值中对变量进行分类?
【发布时间】:2021-11-03 14:27:21
【问题描述】:

新的 R 用户。我已经测量了一堆公司标志的颜色(色调)。每个徽标的观察次数可以不同。我的数据格式如下:

Industry <- c("Fossil", "Fossil", "Fossil", "Fossil", "Fossil", "Renewable", "Renewable", "Renewable")
Logo <- c("Petrox", "Petrox", "Petrox", "Petrox", "Petrox", "Windo", "Windo", "Windo")
Hue <- c(36, 37, 43, 185, 190, 356, 310, 25)
df <- data.frame(Industry, Logo, Hue)

我一直在尝试使用 cut() 为示例中的每个徽标合并 df$Hue 变量。

# set up cut-off values 
breaks <- c(0,45,90,135,180,225,270,315,360)

# specify interval/bin labels
labels <- c("[0-45)","[45-90)", "[90-135)", "[135-180)", "[180-225)", "[225-270)","[270-315)", "[315-360)")

我想得到一个数据框,每个徽标一行,每个 bin 一列,它计算一个间隔内的观察次数对于每个徽标,如下所示:

Ind Logo [0-45) [45-90) [90-135) [135-180) [180-225) [225-270) [270-315) [315-360)
Fossil Petrol 3 0 0 0 2 0 0 0
Renewable Wind 1 0 0 0 0 0 1 1

我一直在寻找好的解决方案,但到目前为止还没有找到有用的答案。有没有一种简单的方法可以使用cut() 函数subset()split()?到目前为止,我对解决方案的搜索无济于事。我确信这是我需要的一个非常简单的东西。

【问题讨论】:

    标签: r loops subset categories binning


    【解决方案1】:

    可以使用cut对数据进行分类,complete序列,使用pivot_wider获取宽格式数据。

    library(dplyr)  
    library(tidyr)
    
      
    df %>%
      count(Industry, Logo, Hue = cut(Hue, breaks, labels)) %>%
      complete(Industry, Hue = labels, fill = list(n = 0)) %>%
      fill(Logo) %>%
      arrange(match(Hue, labels)) %>%
      pivot_wider(names_from = Hue, values_from = n)
    
    #   Industry  Logo   `[0-45)` `[45-90)` `[90-135)` `[135-180)` `[180-225)` `[225-270)` `[270-315)` `[315-360)`
    #  <chr>     <chr>     <dbl>     <dbl>      <dbl>       <dbl>       <dbl>       <dbl>       <dbl>       <dbl>
    #1 Fossil    Petrox        3         0          0           0           2           0           0           0
    #2 Renewable Windo         1         0          0           0           0           0           1           1
    

    【讨论】:

    • 是的,这正是我需要的。非常感谢。我已经盯着它看了好几天了。
    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2021-03-03
    • 2023-01-27
    • 2020-12-31
    相关资源
    最近更新 更多