根据名称 R dplyr 乘以某些列

multiply certain columns based on name R dplyr

我有以下形式的数据集

Product   1/1/2020.x  1/1/2019.x  1/1/2018_x  1/1/2020.y  1/1/2019.y  1/1/2018.y
   1          10          11          10           1           1           1
   2          12          12           0           2           1           0
   3          20          10          12           2           1           2
   4          30           3           1           3           3           1
   5          21           3           1           1           3           1

我想创建一个新的数据集,其中每对 x 和 y 列(相同的日期前缀)相乘。我无法手动完成,因为列数超过 100。生成的数据框应具有以下形式。

Product   1/1/2020     1/1/2019    1/1/2018      
   1          10          11          10          
   2          24          12           0           
   3          40          10          24            
   4          90           9           1            
   5          21           9           1            

使用 tidyverse

library(tidyverse)
df <- read.table(text = "Product   1/1/2020.x  1/1/2019.x  1/1/2018.x  1/1/2020.y  1/1/2019.y  1/1/2018.y
   1          10          11          10           1           1           1
   2          12          12           0           2           1           0
   3          20          10          12           2           1           2
   4          30           3           1           3           3           1
   5          21           3           1           1           3           1", header = T)
df %>% 
  pivot_longer(-Product, names_to = c("set", ".value"), names_pattern = "(.*)(.)") %>% 
  transmute(Product, set, z = x * y) %>% 
  pivot_wider(Product, names_from = set, values_from = z)
#> # A tibble: 5 x 4
#>   Product X1.1.2020. X1.1.2019. X1.1.2018.
#>     <int>      <int>      <int>      <int>
#> 1       1         10         11         10
#> 2       2         24         12          0
#> 3       3         40         10         24
#> 4       4         90          9          1
#> 5       5         21          9          1

reprex package (v1.0.0)

创建于 2021-02-03