如何在 R 中按列名交换数据框中变量之间的值

How to swap values between variables in a data frame by column name in R

我想按列名交换以下数据集的值。例如,将 beta0_C1 and beta0_C2 的值交换为行 10 to 15,其余值保持不变。类似地,对于行 10 to 15,交换 beta1_C1 and beta1_C2 的值。同样对于 beta2_C1 and beta2_C2beta3_C1 and beta3_C2

beta0_C1  beta1_C1     beta2_C1      beta3_C1 beta0_C2   beta1_C2   beta2_C2
1  6.010537 0.2826006  0.001931834 -0.0014162495 6.862525 -0.7267671 0.12065368
2  6.182425 0.1633226  0.025748699 -0.0028515529 6.780775 -0.6686269 0.10548767
3  6.222667 0.1109463  0.036438064 -0.0034054813 6.891512 -0.7372192 0.11895311
4  5.980246 0.3095103 -0.002670511 -0.0011975572 6.677035 -0.5774936 0.08990028
5  6.146192 0.1661733  0.024968028 -0.0027346213 6.881571 -0.7439543 0.11835484
6  6.056259 0.2374753  0.010833872 -0.0019526540 7.094971 -0.8504940 0.13648015
7  6.051281 0.2265750  0.017030676 -0.0024138722 6.829044 -0.7180662 0.12121844
8  5.911484 0.3628966 -0.014161483 -0.0005192893 6.784079 -0.6090060 0.09075940
9  5.956709 0.3486160 -0.011525364 -0.0006776760 6.934137 -0.7821656 0.12996924
10 6.010721 0.2821788  0.002475369 -0.0014508507 6.810553 -0.7140603 0.12471406
11 6.021261 0.3180654 -0.004986709 -0.0010968281 6.708342 -0.6259794 0.10697798
12 6.171459 0.2020801  0.015380862 -0.0021379484 6.592252 -0.5040888 0.07813420
13 6.103334 0.2432321  0.010022319 -0.0019386513 6.831204 -0.6854066 0.11129609
14 5.989656 0.3026038 -0.003007319 -0.0011073984 6.782081 -0.6822204 0.10769549
15 6.024628 0.2786942  0.001861784 -0.0014022176 6.864881 -0.7299905 0.12030466
16 6.023082 0.2707312  0.008308583 -0.0019947781 6.850565 -0.7136916 0.11551886
17 5.988829 0.3267394 -0.007576506 -0.0008493887 6.882956 -0.7739330 0.13467615
18 6.072949 0.2744519  0.002846329 -0.0014917373 6.886863 -0.7853582 0.13512568
19 6.030894 0.2693881  0.006378019 -0.0017875603 6.842824 -0.7238131 0.11835479
20 6.197286 0.1311579  0.036005746 -0.0035338268 6.807729 -0.6549960 0.10400631
       beta3_C2
1  -0.005112708
2  -0.003982831
3  -0.004824895
4  -0.003356916
5  -0.004724677
6  -0.005657009
7  -0.005200557
8  -0.003065364
9  -0.005408715
10 -0.005551546
11 -0.004516814
12 -0.002726879
13 -0.004493288
14 -0.004053661
15 -0.004913402
16 -0.004609239
17 -0.006101912
18 -0.005945182
19 -0.004801623
20 -0.004151904

感谢任何帮助。

鉴于此输入:

(df1 <- as.data.frame(matrix(1:12, ncol = 3)))
#  V1 V2 V3
#1  1  5  9
#2  2  6 10
#3  3  7 11
#4  4  8 12

您可以使用rev

df1[1:2, c("V2", "V3")] <- rev(df1[1:2, c("V2", "V3")])

结果

df1
#  V1 V2 V3
#1  1  9  5
#2  2 10  6
#3  3  7 11
#4  4  8 12

写成 rowscols

的函数
f <- function(data, rows, cols) {
  data[rows, cols] <- rev(data[rows, cols])
  data
}

f(df1, 1:2, c("V2", "V3"))