改变列以获得唯一值,转置另一列并添加这些唯一值的百分比

Mutating columns to get Unique Values, transpose another column and add the percentage of those unique values

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

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) library(dplyr) library(tidyr) 按此顺序。我提到的原因是,如果你改变它的工作顺序,我会在某个地方阅读,但最终会弄乱结果。

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

使用 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-02-25 创建

问题是它需要按 'Code' 和 'Item'

进行分组
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