在R中更有效地进行这些操作

时间:2016-03-22 12:42:30

标签: r function data-manipulation

我想在R

中进行这些操作
-Coefs["(Intercept)", "Estimate"]/Coefs["Conc", "Estimate"]

-(Coefs["(Intercept)", "Estimate"] + Coefs["TypeB", "Estimate"])/(Coefs["Conc", "Estimate"] + Coefs["Conc:TypeB", "Estimate"])

-(Coefs["(Intercept)", "Estimate"] + Coefs["TypeC", "Estimate"])/(Coefs["Conc", "Estimate"] + Coefs["Conc:TypeC", "Estimate"])

这是针对虚拟数据的。

Coefs <-
  structure(
    c(-0.655176424546434, 0.0716295137099851, -0.346864961556839, 
      -0.662301791917405, -0.0101306429956384, 0.0333684345574175, 
       0.235567215467725, 0.0115201651054553, 0.33677014835764, 0.354186003909237, 
       0.0155441436341732, 0.0178799013519851, -2.78127167757858, 6.21775061852761, 
      -1.02997538008766, -1.86992649231595, -0.65173374835308, 1.8662538400254, 
       0.00541464034248888, 5.04332248955962e-10, 0.303021562987807, 
       0.0614940263243856, 0.514572947373205, 0.0620058596249395), 
    .Dim = c(6L, 4L), 
    .Dimnames = list(
                  c("(Intercept)", "Conc", "TypeB", "TypeC","Conc:TypeB", "Conc:TypeC")
                , c("Estimate", "Std. Error", "z value", "Pr(>|z|)"))
     )
                                                                                                                        "Pr(>|z|)")))

Coefs
               Estimate Std. Error    z value     Pr(>|z|)
(Intercept) -0.65517642 0.23556722 -2.7812717 5.414640e-03
Conc         0.07162951 0.01152017  6.2177506 5.043322e-10
TypeB       -0.34686496 0.33677015 -1.0299754 3.030216e-01
TypeC       -0.66230179 0.35418600 -1.8699265 6.149403e-02
Conc:TypeB  -0.01013064 0.01554414 -0.6517337 5.145729e-01
Conc:TypeC   0.03336843 0.01787990  1.8662538 6.200586e-02


-Coefs["(Intercept)", "Estimate"]/Coefs["Conc", "Estimate"]

[1] 9.146738

-(Coefs["(Intercept)", "Estimate"] + Coefs["TypeB", "Estimate"])/(Coefs["Conc", "Estimate"] + Coefs["Conc:TypeB", "Estimate"])

[1] 16.29366


-(Coefs["(Intercept)", "Estimate"] + Coefs["TypeC", "Estimate"])/(Coefs["Conc", "Estimate"] + Coefs["Conc:TypeC", "Estimate"])


[1] 12.54766

对于真实数据,我必须做很多计算。如何通过Type因子的多个级别更有效地完成此任务?

1 个答案:

答案 0 :(得分:1)

使用grepl

-(Coefs["(Intercept)", "Estimate"] + Coefs[grepl("^Type.$", rownames(Coefs)), "Estimate"])/
  (Coefs["Conc", "Estimate"] + Coefs[grepl("^Conc:Type.$", rownames(Coefs)), "Estimate"])   
#   TypeB    TypeC 
#16.29366 12.54766