尝试将数据框中的值替换为其他值

时间:2017-08-29 20:08:22

标签: r

我有一个矢量列表L1和一个数据帧df2。我想从df2获取值并用这些值替换L1的值。例如,当L1的ABCC10表示“TCGA_DD_A1EG”时,我想将其替换为第1行(ABCC10)第3列(TCGA.DD.A1EG)中的值2.193205。我想用每一个价值来做这件事。

L1看起来像这样:

$ABCC10
[1] "TCGA_DD_A1EG" "TCGA_FV_A3R2" "TCGA_FV_A3I0" "TCGA_DD_A1EH" "TCGA_FV_A23B"

$ACBD6
[1] "TCGA_DD_A1EH" "TCGA_DD_A3A8" "TCGA_ES_A2HT" "TCGA_DD_A1EG" "TCGA_DD_A1EB"

df2看起来像这样:

       TCGA.BC.A10Q TCGA.DD.A1EB TCGA.DD.A1EG TCGA.DD.A1EH TCGA.DD.A1EI TCGA.DD.A3A6 TCGA.DD.A3A8
ABCC10     2.540764    0.4372165     2.193205     3.265756    0.6060301     2.927072    0.6799514
ACBD6      1.112432    0.4611697     1.274129     1.802985   -0.0475743     1.071064    0.4336301
       TCGA.ES.A2HT TCGA.FV.A23B TCGA.FV.A3I0 TCGA.FV.A3R2
ABCC10  -0.08129554    2.2963764     3.196518    0.8595943
ACBD6    1.76935812    0.3644397     1.392206    1.0282030

2 个答案:

答案 0 :(得分:1)

一种方法可能就像

df1 = list(ABCC10 = c("TCGA_DD_A1EG", "TCGA_FV_A3R2", "TCGA_FV_A3I0", "TCGA_DD_A1EH", "TCGA_FV_A23B"),
           ACBD6 = c("TCGA_DD_A1EH", "TCGA_DD_A3A8", "TCGA_ES_A2HT", "TCGA_DD_A1EG", "TCGA_DD_A1EB"))

df2 = data.frame(TCGA.BC.A10Q = c(2.540764, 1.112432),
                 TCGA.DD.A1EB = c(0.4372165, 0.4611697),
                 TCGA.DD.A1EG = c(2.193205, 1.274129),
                 TCGA.DD.A1EH = c(3.265756, 1.802985),
                 TCGA.DD.A1EI = c(0.6060301, -0.0475743),
                 TCGA.DD.A3A6 = c(2.927072, 1.071064),
                 TCGA.DD.A3A8 = c(0.6799514, 0.4336301),
                 TCGA.ES.A2HT = c(-0.08129554, 1.76935812),
                 TCGA.FV.A23B = c(2.2963764, 0.3644397),
                 TCGA.FV.A3I0 = c(3.196518, 1.392206),
                 TCGA.FV.A3R2 = c(0.8595943, 1.0282030),
                 row.names = c('ABCC10', 'ACBD6'))

for(i in 1:length(df1)){
  for(j in 1:length(df1[[1]])){
    df1[names(df1)[i]][[1]][j] = df2[names(df1)[i],gsub("_",".",df1[names(df1)[i]][[1]][j])]
  }
}

输出是:

$ABCC10
[1] "2.193205"  "0.8595943" "3.196518"  "3.265756"  "2.2963764"

$ACBD6
[1] "1.802985"   "0.4336301"  "1.76935812" "1.274129"   "0.4611697" 

希望这有帮助!

答案 1 :(得分:0)

也许以下会这样做。 首先,编制一些数据,listdata.frame

df1 <- list(A = letters[1:3], B = letters[5:7])

df2 <- data.frame(a = rnorm(2), b = rnorm(2), c = rnorm(2),
                  e = rnorm(2), f = rnorm(2), g = rnorm(2))
row.names(df2) <- c('A', 'B')

现在代码。

for(i in seq_along(df1)){
    x <- gsub("_", ".", df1[[i]])
    inx <- match(x, names(df2))
    df1[[i]] <- df2[i, inx]
}
df1

在我的测试中,它做了你想要的。如果它不适合你的真正问题,那就这么说吧。