如何从具有相同前缀的 .y 中减去多个 .x

Tar*_*Jae 5 r difference dplyr

我有这个小玩意:

# A tibble: 2 x 8
    a.x   b.x   c.x   d.x   a.y   b.y   c.y   d.y
  <int> <int> <int> <int> <int> <int> <int> <int>
1    13    13    12    11     7     1     4     2
2    17    11     0     0    16     2     0     0
Run Code Online (Sandbox Code Playgroud)
df <- structure(list(a.x = c(13L, 17L), b.x = c(13L, 11L), c.x = c(12L, 
0L), d.x = c(11L, 0L), a.y = c(7L, 16L), b.y = 1:2, c.y = c(4L, 
0L), d.y = c(2L, 0L)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))
Run Code Online (Sandbox Code Playgroud)

我想计算: a.x - a.y , b.x - b.y, c.x - c.y, 等等....

我想要的输出:

    a.x   b.x   c.x   d.x   a.y   b.y   c.y   d.y     a     b     c     d
  <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1    13    13    12    11     7     1     4     2     6    12     8     9
2    17    11     0     0    16     2     0     0     1     9     0     0
Run Code Online (Sandbox Code Playgroud)

我可以通过以下方式实现这一目标:

df %>% 
    mutate(a = a.x-a.y,
           b = b.x-b.y,
           c = c.x-c.y,
           d = d.x-d.y)
Run Code Online (Sandbox Code Playgroud)

我想学习:

  1. 如何提取新列名的前缀。
  2. 自动计算.x - .y。

akr*_*run 4

一种方法是cur_column- 循环遍历列,通过将 'x' 更改为 'y'值来ends_with .x替换列名 ( ) 中的子字符串,减去并更改列名cur_column()get.names

library(dplyr)
library(stringr)
df %>% 
   mutate(across(ends_with('.x'),
     ~ . - get(str_replace(cur_column(), 'x', 'y')), 
         .names = "{str_remove(.col, fixed('.x'))}"))
Run Code Online (Sandbox Code Playgroud)

-输出

# A tibble: 2 x 12
    a.x   b.x   c.x   d.x   a.y   b.y   c.y   d.y     a     b     c     d
  <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1    13    13    12    11     7     1     4     2     6    12     8     9
2    17    11     0     0    16     2     0     0     1     9     0     0
Run Code Online (Sandbox Code Playgroud)

或通过重塑pivot_longer

library(tidyr)
df %>%
     mutate(rn = row_number()) %>%
     pivot_longer(cols = -rn, names_to = c(".value"), 
          names_pattern = "(.)\\..*") %>% 
     group_by(rn) %>% 
     summarise(across(everything(), ~ -diff(.))) %>%
     select(-rn) %>%
     bind_cols(df, .)
# A tibble: 2 x 12
 a.x   b.x   c.x   d.x   a.y   b.y   c.y   d.y     a     b     c     d
  <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1    13    13    12    11     7     1     4     2     6    12     8     9
2    17    11     0     0    16     2     0     0     1     9     0     0
Run Code Online (Sandbox Code Playgroud)