Вот решение 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)")
)