如何在R中自动执行列减法?

up9lanfz  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(146)

我想做的是自动化不同列的减法,如果可能的话,我的数据看起来像这样:

colnames <- c("HFW01_V2", "HFW01_V2", "HFW01_V3", "HFW02_V2" ,"HFW02_V3", "HFW03_V2", "HFW03_V3")
df <- tibble( Sample = c("s001", "s002", "s003", "s004", "s005", "s006"),
   HFW01_V2 = 5:8,
   HFW01_V3 = 10:13,
   HFW02_V2 = 15:18,
   HFW02_V3 = 20:23,
   HFW03_V2 = 25:28, 
   HFW03_V3 = 28:31)

我想做的是创建一个新的列,其结果为(HFW01_V3 - HFW01_V2)/HFW01_V2,另一个列为(HFW02_V3 - HFW02_V2)/HFW01_V2,并且在......因为有38个样本,所以可以自动指定??
谢谢〈3

q1qsirdb

q1qsirdb1#

这里有一个尝试,旋转,减去/除以,然后旋转回宽:

library(dplyr)
library(tidyr) # pivot_*
df %>%
  pivot_longer(-Sample, names_pattern = "(.*)_(.*)", names_to = c("hfw", ".value")) %>%
  mutate(diff = (V3 - V2)/V2) %>%
  pivot_wider(id_cols = Sample, names_from = "hfw", values_from = c("V2", "V3", "diff"), names_glue = "{hfw}_{.value}")
# # A tibble: 4 × 10
#   Sample HFW01_V2 HFW02_V2 HFW03_V2 HFW01_V3 HFW02_V3 HFW03_V3 HFW01_diff HFW02_diff HFW03_diff
#   <chr>     <int>    <int>    <int>    <int>    <int>    <int>      <dbl>      <dbl>      <dbl>
# 1 s001          5       15       25       10       20       25      1          0.333          0
# 2 s002          6       16       26       11       21       26      0.833      0.312          0
# 3 s003          7       17       27       12       22       27      0.714      0.294          0
# 4 s004          8       18       28       13       23       28      0.625      0.278          0

数据

df <- structure(list(Sample = c("s001", "s002", "s003", "s004"), HFW01_V2 = 5:8, HFW01_V3 = 10:13, HFW02_V2 = 15:18, HFW02_V3 = 20:23, HFW03_V2 = 25:28, HFW03_V3 = 25:28), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L))
bvjxkvbb

bvjxkvbb2#

这是一个解决方案,花了我一段时间,我不满意100%。我不知何故不能合并线2和3:
感谢@r2evans,他的解决方案对找到我的答案有很大帮助!

library(dplyr)
library(stringr)

df %>%
  mutate(across(ends_with('_V3'), ~ . - get(str_replace(cur_column(), "V3$", "V2")))) %>% 
  transmute(across(ends_with('_V3'), ~ . / get(str_replace(cur_column(), "V3$", "V2")), .names = "diff_{.col}")) %>% 
  bind_cols(df)
diff_HFW01_V3 diff_HFW02_V3 diff_HFW03_V3 Sample HFW01_V2 HFW01_V3 HFW02_V2 HFW02_V3 HFW03_V2 HFW03_V3
          <dbl>         <dbl>         <dbl> <chr>     <int>    <int>    <int>    <int>    <int>    <int>
1         1             0.333         0.2   s001          5       10       15       20       25       30
2         0.833         0.312         0.192 s002          6       11       16       21       26       31
3         0.714         0.294         0.185 s003          7       12       17       22       27       32
4         0.625         0.278         0.179 s004          8       13       18       23       28       33

相关问题