通过根据另一行中另一列的值向数据框中添加列来匹配数据

时间:2020-07-26 04:52:58

标签: r dataframe match

我有一个数据框,其中有许多行必须通过各种条件进行匹配。到目前为止,我一直在为此而苦苦挣扎,并逐渐失去希望我能够解决它的希望。这是我的数据框的示例:

  No Test  Reference Value
  5 OF    3            55
  7 EPM   1            33
  5 H1    -            23
  7 H3    -            22
  5 R1    -            15
  7 R3    -            28
  5 H3    -            60
  7 H1    -            33
  5 R3    -            21
  7 R1    -            18
  5 T     -            20
  7 T     -            17

我的目标是在新列(H,R和T)中获得具有“测试”(OF或EPM)值与其他值(来自不同行)匹配的数据框。必须根据“否”和“参考”列中的条件选择匹配的数据。 “参考”列的值(1或3)指的是行(“测试”列:1 = H1和R1,3 = H3和R3)。仅根据“否”列中的值来匹配“测试”列中带有T的行。 结果示例如下:

  No Test  Reference Value     H     R     T
  5 OF            3    55    60    21    20
  7 EPM           1    33    33    18    17

我感谢您可以提供的任何帮助。非常感谢!!!

1 个答案:

答案 0 :(得分:0)

我已经重新创建了一个场景,试图以我对您情况的最佳理解来模拟您面临的问题。希望它至少应该使您走上寻找所需答案的道路。

您可以将以下代码复制粘贴到R控制台中,以完成所有步骤。

library(dplyr)

## Reproduce the dataframe shown in your example
df <- cbind.data.frame(No = c(5,7,5,7,5,7,5,7,5,7),Test = c('H1','H3','R1','R3','H3','H1','R3','R1','T','T'),Value = c(23,22,15,28,60,33,21,18,20,17))

## Create the final dataframe that will contain all the sorted values
df2 <- cbind.data.frame(No = c(5,7), Test = c('OF','EPM'), Reference = c(3,1), Value = c(55,33), H = c(0,0), R = c(0,0), T = c(0,0) )

## Filling the final table <-- ANSWER TO YOUR QUESTION

for (row in 1:nrow(df))
{
  if(df[row,"No"] == 5){
    if(grepl("3", df[row,"Test"]) |grepl("T", df[row,"Test"]) ){
      df2[1,substr(df[row,"Test"],1,1)] = df[row,"Value"]
    }
  }
  else if(df[row,"No"] == 7){
    if(grepl("1", df[row,"Test"])|grepl("T", df[row,"Test"]) ){
      df2[2,substr(df[row,"Test"],1,1)] = df[row,"Value"]
    }
  }
}

# We now have a new table fully filled according to the logic specified in your example.