我在R中有一个数据框,其中包含异常格式的数据。我想将其转换为常规格式。以下是输入示例-
Brand | Product | Store | Sales
A 35
Prod1 10
Store1 2
Store2 3
Store3 5
Prod2 25
Store1 10
Store2 15
基本上,该文件包含商店级别的数据,然后在产品和品牌级别的“外部”行中进行汇总。
我正在寻找的输出是-
Brand | Product | Store | Sales
A Prod1 Store1 2
A Prod1 Store2 3
A Prod1 Store3 5
A Prod2 Store1 10
A Prod2 Store2 15
如何在R中转换它?
答案 0 :(得分:4)
您可以使用tidyr::fill
:https://tidyr.tidyverse.org/reference/fill.html
最后过滤掉商店中的空行。
df %>%
fill(Brand) %>%
fill(Product) %>%
filter(drop_na(Store))