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

David Winsemius dwinsemius at comcast.net
Wed Dec 2 01:35:57 CET 2015


> On Dec 1, 2015, at 4:32 PM, David Winsemius <dwinsemius at comcast.net> wrote:
> 
> 
>> On Dec 1, 2015, at 2:57 PM, John Sorkin <jsorkin at grecc.umaryland.edu> wrote:
>> 
>> 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!
> 
> It’s telling you there is no column in that dataframe with the name “varscr”.
> 

Actually it’s a matrix, but the same reasoning applies.

— 
> David.
> 
> 
>> 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


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list