修改与列名匹配的值

时间:2019-11-21 17:12:18

标签: r

在下面的数据框中,如果Name列与列名匹配,我试图将(AC,BAT,REC)的相应值带到New_Mutate列。

df1 <-  data.frame(AC=c(1.463437e-04,1.023486e-04,1.584040e-05 ),
                   BAT = c(6.555388e-05,5.471379e-01,6.025364e-06),
                   REC = c(6.541157e-05,9.590567e-05,1.581244e-01),
                   Name = c("BAT", "AC", "REC"))
>df1
            AC          BAT          REC Name
1 0.0001463437 6.555388e-05 6.541157e-05  BAT
2 0.0001023486 5.471379e-01 9.590567e-05   AC
3 0.0000158404 6.025364e-06 1.581244e-01  REC

预期输出:

       AC                       BAT          REC           Name     New_Mutate    
1   1.463437e-04             6.555388e-05 6.541157e-05      BAT     6.555388e-05 
2   1.023486e-04             5.471379e-01 9.590567e-05      AC      1.023486e-04
3   1.584040e-05             6.025364e-06 1.581244e-01      REC     1.581244e-01

3 个答案:

答案 0 :(得分:3)

df1 %>% mutate(new_c = (.)[cbind(row_number(), match(Name, names(.)))])
#            AC          BAT          REC Name        new_c
#1 0.0001463437 6.555388e-05 6.541157e-05  BAT 6.555388e-05
#2 0.0001023486 5.471379e-01 9.590567e-05   AC 0.0001023486
#3 0.0000158404 6.025364e-06 1.581244e-01  REC 1.581244e-01

答案 1 :(得分:3)

您也可以这样做:

df1 %>% 
 rowwise() %>% 
 mutate(new_c = get(paste0(Name)))

         AC        BAT       REC Name      new_c
      <dbl>      <dbl>     <dbl> <fct>     <dbl>
1 0.000146  0.0000656  0.0000654 BAT   0.0000656
2 0.000102  0.547      0.0000959 AC    0.000102 
3 0.0000158 0.00000603 0.158     REC   0.158 

答案 2 :(得分:1)

我们可以使用base R来完成

df1$new_c<- df1[-4][cbind(seq_len(nrow(df1)), match(df1$Name, colnames(df1)[-4])]