Как распределить мой набор данных по различным категориям - PullRequest
0 голосов
/ 14 марта 2020

Я до сих пор новичок в R. Может ли кто-нибудь помочь мне разобраться, как распределить мой набор данных по различным категориям?

Вот что я получил в R.

enter image description here

Значения с "кодом товара" попадают в "широкую категорию", другие находятся в подкатегориях (фактические товары). Итак, теперь я хочу разделить значения в подкатегориях (то есть значения с кодом NA) и поместить его в третий столбец ((например, столбец № 1 - «Код товара», столбец № 2 - «широкая категория», а столбец - столбец). # 3 - это "Specifi c items")

В частности, я получу sh конечный результат, который будет выглядеть следующим образом:

enter image description here

I ' Я думаю об использовании команды spread(), но, похоже, она не работает. Может ли кто-нибудь дать мне несколько советов о моих следующих шагах?

(я думаю об определении "широких категорий" в качестве переменной и "подкатегории" в качестве другой переменной, а затем я мог бы распространить таблицу? Не уверен)

Ответы [ 2 ]

2 голосов
/ 14 марта 2020

Вот решение tidyverse, которое вы можете рассмотреть. Я добавлю примеры данных, чтобы другие могли предоставить альтернативы.

library(tidyverse)

df %>%
  fill(Item.Code) %>%
  group_by(Item.Code) %>%
  mutate(Category = first(Item)) %>%
  slice(2:n())

Вывод

# A tibble: 12 x 3
# Groups:   Item.Code [3]
   Item.Code Item                                        Category                        
       <dbl> <fct>                                       <fct>                           
 1       221 Prunus amygdalus                            Almonds, with shell             
 2       221 Almond (Prunus dulcis or Amygdalus communis Almonds, with shell             
 3       711 Pimpinella anisum (aniseed)                 Anise, badian, fennel, coriander
 4       711 Illicium verum (star anise)                 Anise, badian, fennel, coriander
 5       711 Carum carvi                                 Anise, badian, fennel, coriander
 6       711 Coriandrum sativum (coriander               Anise, badian, fennel, coriander
 7       711 Cuminum cyminum (cumin)                     Anise, badian, fennel, coriander
 8       711 Foeniculum vulgare (fennel)                 Anise, badian, fennel, coriander
 9       711 Juniperus communis (common juniper)         Anise, badian, fennel, coriander
10       800 Agave                                       Agave fibres nes                
11       800 Agave fourcroydes (Henequen)                Agave fibres nes                
12       800 Agave americana (century plant)             Agave fibres nes

Данные

df <- data.frame(
  Item.Code = c(800, NA, NA, NA, 221, NA, NA, 711, NA, NA, NA, NA, NA, NA, NA),
  Item = c("Agave fibres nes", "Agave", "Agave fourcroydes (Henequen)", "Agave americana (century plant)", "Almonds, with shell",
           "Prunus amygdalus", "Almond (Prunus dulcis or Amygdalus communis", "Anise, badian, fennel, coriander",
           "Pimpinella anisum (aniseed)", "Illicium verum (star anise)", "Carum carvi", "Coriandrum sativum (coriander",
           "Cuminum cyminum (cumin)", "Foeniculum vulgare (fennel)", "Juniperus communis (common juniper)")
)
0 голосов
/ 15 марта 2020

Мы также можем использовать data.table

library(data.table)
library(zoo)
setDT(df)[,  c(.SD[-1], .(Category = first(Item))),.(Item.Code = na.locf0(Item.Code))]
#    Item.Code                                        Item                         Category
# 1:       800                                       Agave                 Agave fibres nes
# 2:       800                Agave fourcroydes (Henequen)                 Agave fibres nes
# 3:       800             Agave americana (century plant)                 Agave fibres nes
# 4:       221                            Prunus amygdalus              Almonds, with shell
# 5:       221 Almond (Prunus dulcis or Amygdalus communis              Almonds, with shell
# 6:       711                 Pimpinella anisum (aniseed) Anise, badian, fennel, coriander
# 7:       711                 Illicium verum (star anise) Anise, badian, fennel, coriander
# 8:       711                                 Carum carvi Anise, badian, fennel, coriander
# 9:       711               Coriandrum sativum (coriander Anise, badian, fennel, coriander
#10:       711                     Cuminum cyminum (cumin) Anise, badian, fennel, coriander
#11:       711                 Foeniculum vulgare (fennel) Anise, badian, fennel, coriander
#12:       711         Juniperus communis (common juniper) Anise, badian, fennel, coriander

данные

df <- data.frame(
  Item.Code = c(800, NA, NA, NA, 221, NA, NA, 711, NA, NA, NA, NA, NA, NA, NA),
  Item = c("Agave fibres nes", "Agave", "Agave fourcroydes (Henequen)", "Agave americana (century plant)", "Almonds, with shell",
           "Prunus amygdalus", "Almond (Prunus dulcis or Amygdalus communis", "Anise, badian, fennel, coriander",
           "Pimpinella anisum (aniseed)", "Illicium verum (star anise)", "Carum carvi", "Coriandrum sativum (coriander",
           "Cuminum cyminum (cumin)", "Foeniculum vulgare (fennel)", "Juniperus communis (common juniper)")
)
...