【问题标题】:Mutating columns to get Unique Values, transpose another column and add the percentage of those unique values变异列以获取唯一值,转置另一列并添加这些唯一值的百分比
【发布时间】:2021-05-28 01:51:17
【问题描述】:

我有一个数据集,我的子集如下所示:

Item Code Percentage
10000 123 0.2
10001 134 0.98
10001 152 0.02
10002 123 0.68
10003 123 1
10002 178 0.32
10004 189 1

我想找到一种转置方式,只保留 A 列中的唯一值,B 列根据唯一值分散到不同的列中,百分比填充在这些值中。请查看我希望最终确定的数据示例:

Item 123 134 152 178 189
10000 0.2 0 0 0 0
10001 0 0.98 0.02 0 0
10002 0.68 0 0 0.3 0
10003 1 0 0 0 0
10004 0 0 0 0 1

我目前使用的格式如下“骨架”:

       df <-df %>%
       group_by(Item) %>%
       mutate(n = row_number()) %>%
       spread(Code, Percentage)

按照这种结构,我仍然会在 A 列中得到重复的值(不是唯一的)。我确实加载了库(plyr) 图书馆(dplyr)图书馆(tidyr)按此顺序。我提到的原因是,如果您切换它的工作顺序,我会在某处阅读,但最终会弄乱结果。

如果您需要更多信息,请告诉我。谢谢!

【问题讨论】:

标签: r tidyr plyr dplyr


【解决方案1】:

使用 tidyverse

library(tidyverse)

df <- read.table(text = "Item   Code    Percentage
10000   123 0.2
10001   134 0.98
10001   152 0.02
10002   123 0.68
10003   123 1
10002   178 0.32
10004   189 1", header = T)

pivot_wider(
  data = df, 
  id_cols = Item, 
  names_from = Code, 
  values_from = Percentage, 
  values_fill = 0
)
#> # A tibble: 5 x 6
#>    Item `123` `134` `152` `178` `189`
#>   <int> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 10000  0.2   0     0     0        0
#> 2 10001  0     0.98  0.02  0        0
#> 3 10002  0.68  0     0     0.32     0
#> 4 10003  1     0     0     0        0
#> 5 10004  0     0     0     0        1

reprex package (v1.0.0) 于 2021-02-25 创建

使用 data.table

library(data.table)
setDT(df)
dcast(data = df, formula = Item ~ Code, value.var = "Percentage", fill = 0)
#>     Item  123  134  152  178 189
#> 1: 10000 0.20 0.00 0.00 0.00   0
#> 2: 10001 0.00 0.98 0.02 0.00   0
#> 3: 10002 0.68 0.00 0.00 0.32   0
#> 4: 10003 1.00 0.00 0.00 0.00   0
#> 5: 10004 0.00 0.00 0.00 0.00   1

reprex package (v1.0.0) 于 2021 年 2 月 25 日创建

【讨论】:

    【解决方案2】:

    问题是它需要同时按“代码”和“项目”进行分组

    library(dplyr)
    library(tidyr)
    df %>%
       group_by(Code, Item) %>%
       mutate(n = row_number()) %>%
       ungroup %>%
       spread(Code, Percentage, fill = 0) %>%
       select(-n)
    

    -输出

    # A tibble: 5 x 6
    #   Item `123` `134` `152` `178` `189`
    #  <int> <dbl> <dbl> <dbl> <dbl> <dbl>
    #1 10000  0.2   0     0     0        0
    #2 10001  0     0.98  0.02  0        0
    #3 10002  0.68  0     0     0.32     0
    #4 10003  1     0     0     0        0
    #5 10004  0     0     0     0        1
    

    【讨论】:

      猜你喜欢
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2021-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多