使用 gather 和 ... 整理数据框?

Tidying a dataframe using gather and ...?

我有一个具有以下结构的数据框:

record <- c(seq_along(1:10))
store <- c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
week <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)
sales_1 <- c(3, 3, 3, 3, 3, 2, 5, 1, 2, 10)
sales_2 <- c(1, 2, 4, 5, 6, 2, 3, 6, 1, 8)
price_1 <- runif(10, 2, 6)
price_2 <- runif(10, 2, 6)

df <- data_frame(record, store, week, sales_1, sales_2, price_1, price_2)

假设我想收集它并对其进行转换,从而保留 'record'、'store' 和 'week' 列,但随后我还创建了一个名为 [=22 的新列=],表示每个 'sales_' 和 'price_' 列末尾的尾随数字。最后,我将 'sales' 和 'price' 列的值合并为两列(简单地 'sales' 和 'price')。结果看起来像这样:

record | store | week | category | sales | price
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1        1      1        1         3      2.51
  1        1      1        2         1      5.50
  2        2      1        1         3      4.86

最初的讨论来自。感谢@markdly 预测我会在这里结束...

您可以 gather salesprice 列,将 key 分开进入新的 header 和 类别 然后 spread header:

df %>% 
    gather(key, val, sales_1:price_2) %>% 
    separate(key, c('header', 'category'), sep='_') %>% 
    spread(header, val)

# A tibble: 20 x 6
#   record store  week category    price sales
# *  <int> <dbl> <dbl>    <chr>    <dbl> <dbl>
# 1      1     1     1        1 5.005186     3
# 2      1     1     1        2 4.184387     1
# 3      2     2     1        1 3.790764     3
# 4      2     2     1        2 4.668122     2
# ...