[R] Function calling a function, column name not passed properly

John Sorkin jsorkin at grecc.umaryland.edu
Tue Dec 1 23:57:07 CET 2015


I am trying to write a function that calls a function. The first call to SmallFn works without any problem, printing both the passed data and the column Wstscr. The second call does not work (error, Error in d[, column] : subscript out of bounds). 
 
The first call shows what I am trying to do with the second call. I am passing to the outer function doit12 the beginning of the name of the column that I want to access (Wst). doit12 creates the full name of the column (Wstscr) by using varxx <- deparse(susbstitute(variable)) and varscr <- paste(varxx,"scr",sep=""). I can access the column in doit12 as seen by the results of   print(data[,varscr]).
 
SmallFn works when it is called using SmallFn(Wstscr,data), but fails when called with SmallFn(varscr,data). I don't understand why the second call fails. varscr was shown to represent Wstscr.
 
Please tell my why the second call is not working, please put me out of one-full day of misery!
 
Thank you,
John
 
 
 

mydata <- cbind(   patient_id=c(10163,10987,19882,19899,20104,20105,20167,20318,20338,20392),
                   Wstscr=c(139.00,NA,101.80,103.00,76.40,116.00,139.80,111.31,NA,150.00))            
mydata     
 
doit12 <-function(variable,data) {
  
  varxx <- deparse(substitute(variable))
  cat("varxx created from first deparse substitute=",varxx,"\n")
  varscr <- paste(varxx,"scr",sep="")
  cat("1varscr=",varscr,"\n")
  cat("Data inside doit12\n")
  print(data)
  cat("Print the Wstscr column of data. varscr created using paste after deparse substitute\n")
  print(data[,varscr])
  cat("\n\n")
  
  SmallFn <- function(v,d) {
    cat("\nInside SmallFn\n")
    zz <-match.call()
    column <- deparse(substitute(v))
    cat("column=",column,"\n")
    cat("The results of match.call\n")
    print(zz)
    print("Hello world!")
    print(d)
    print(d[,column])
  }
  SmallFn(Wstscr,data)
  SmallFn(varscr,data)
}
doit12(Wst,mydata)
John David Sorkin M.D., Ph.D.
Professor of Medicine
Chief, Biostatistics and Informatics
University of Maryland School of Medicine Division of Gerontology and Geriatric Medicine
Baltimore VA Medical Center
10 North Greene Street
GRECC (BT/18/GR)
Baltimore, MD 21201-1524
(Phone) 410-605-7119
(Fax) 410-605-7913 (Please call phone number above prior to faxing) 

Confidentiality Statement:
This email message, including any attachments, is for the sole use of the intended recipient(s) and may contain confidential and privileged information. Any unauthorized use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply email and destroy all copies of the original message. 


More information about the R-help mailing list