简体   繁体   中英

Searching for partial variable names within a function in R

I have several sets of variables with a shared common string: t75.t0.fc, t75.t0.pval, t75.sig.vol, t75.vol.label to be exact. It would be nice if I could write a generic function where all I have to type is the t75 to pull up these variables within a function which ultimately will make a plot. I need to make lots of plots so I don't want to have to input the 4 unique variables every time. I tried first just replacing the t75 with x throughout my plotting function but it doesn't work. then I tried this, which also doesn't work. Is there some kind of 'escape' key for searching variable names/regex within functions?

first searching for t75 in the colnames of my df returns them all including others I don't want to use in my function:

grep("t75",colnames(WT.protg.merge.vols),value=T)

returns

 [1] "imp.t75.Rep1.WT"             "t0.scaled.imp.t75.Rep1.WT"   "mean.scaled.imp.t75.Rep1.WT" "imp.t75.Rep2.WT"            
 [5] "t0.scaled.imp.t75.Rep2.WT"   "mean.scaled.imp.t75.Rep2.WT" "t75.WT"                      "mean.t75.WT"                
 [9] "avg.imp.t75.WT"              "fc.t75_v_t0"                 "t75.t0.fc"                   "t75.t0.pval"                
[13] "t75.sig.vol"                 "t75.vol.label"  

but

time.plot<-function(df,x){
     cols<-grep("x",colnames(df),value=T)
     return(cols)
}

time.plot(WT.protg.merge.vols,t75)

returns

character(0)

Using quotes withOUT but not withIN the function solves the issue and I can work with this. Thanks @divibisan

time.plot<-function(df,x){
    fc.cols<-grep(x,colnames(df),value=T)
    return(fc.cols)
}

time.plot(WT.protg.merge.vols,"t75")
 [1] "imp.t75.Rep1.WT"             "t0.scaled.imp.t75.Rep1.WT"   "mean.scaled.imp.t75.Rep1.WT" "imp.t75.Rep2.WT"            
 [5] "t0.scaled.imp.t75.Rep2.WT"   "mean.scaled.imp.t75.Rep2.WT" "t75.WT"                      "mean.t75.WT"                
 [9] "avg.imp.t75.WT"              "fc.t75_v_t0"                 "t75.t0.fc"                   "t75.t0.pval"                
[13] "t75.sig.vol"                 "t75.vol.label"     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM