r多列减法

时间:2018-10-10 01:47:01

标签: r dplyr subtraction

我的数据集的简化版本如下所示。

 Z_dog1_mu1  Z_dog2_mu1  Z_dog3_mu1  Z_cat1_mu1  Z_cat2_mu1   Z_cat3_mu1                                                
 0.0000      0.0000      0.0001      0.0005      0.0043       0.0045   
 0.0039     -0.0016     -0.0102     -0.0009      0.0421      -0.0139
-0.0380     -0.0733      0.0196      0.0261      0.0628       0.0463
-0.1036      0.0784     -0.0529      0.1053     -0.0511      -0.0138

我正在尝试从cat *列中减去dog *列

 df$diff1 <- df$Z_dog1_mu1   -  df$Z_cat1_mu1
 df$diff2 <- df$Z_dog2_mu1   -  df$Z_cat2_mu1
 df$diff3 <- df$Z_dog3_mu1   -  df$Z_cat3_mu1  

如何在不手动减去每一列的情况下更高效,更快地执行此操作,如上所述。我大约有100条狗栏(Z_dog1_mu1...Z_dog100_mu1)和100条猫栏(Z_cat1_mu1...Z_cat100_mu1) /。任何建议都非常有用。

1 个答案:

答案 0 :(得分:2)

我们分别将“狗”列和“猫”列子集,然后进行减法

nmdog <- grep("^Z_dog\\d+_mu", names(df))
nmcat <- grep("^Z_cat\\d+_mu", names(df))
df[paste0("diff", seq_along(nmdog))] <- df[nmdog] - df[nmcat]
df
#  Z_dog1_mu1 Z_dog2_mu1 Z_dog3_mu1 Z_cat1_mu1 Z_cat2_mu1 Z_cat3_mu1   diff1   diff2   diff3
#1     0.0000     0.0000     0.0001     0.0005     0.0043     0.0045 -0.0005 -0.0043 -0.0044
#2     0.0039    -0.0016    -0.0102    -0.0009     0.0421    -0.0139  0.0048 -0.0437  0.0037
#3    -0.0380    -0.0733     0.0196     0.0261     0.0628     0.0463 -0.0641 -0.1361 -0.0267
#4    -0.1036     0.0784    -0.0529     0.1053    -0.0511    -0.0138 -0.2089  0.1295 -0.0391

注意:如示例中所示,我们假设“ dog”列序列与“ cat”列序列相对应,即1:100

数据

df <- structure(list(Z_dog1_mu1 = c(0, 0.0039, -0.038, -0.1036), Z_dog2_mu1 = c(0, 
-0.0016, -0.0733, 0.0784), Z_dog3_mu1 = c(1e-04, -0.0102, 0.0196, 
-0.0529), Z_cat1_mu1 = c(5e-04, -9e-04, 0.0261, 0.1053), Z_cat2_mu1 = c(0.0043, 
0.0421, 0.0628, -0.0511), Z_cat3_mu1 = c(0.0045, -0.0139, 0.0463, 
-0.0138)), class = "data.frame", row.names = c(NA, -4L))