[R] writing a function that will refer to the elements of a dataframe much as is done by lm

David Winsemius dwinsemius at comcast.net
Tue Oct 13 02:25:31 CEST 2015


On Oct 12, 2015, at 3:11 PM, John Sorkin wrote:

> I am trying to learn how  to write R functions (really to program in R). I want to write a function that will allow me to refer to the elements of a data frame by column name, much as is done in lm. I can't seem to get the syntax correct. I want the function to print the elements of data2[,"Mo6MONO"]
> 
> data2 <- data.frame(POSTHHMONO=c(1,2,3,4),Mo6MON=c(10,11,12,13))
> data2
> doit<- function(pre,post,data) {
>  element <- deparse(substitute(pre))
>  print(element)
>  frame <- deparse(substitute(data))
>  print(frame)
>  print(frame$element)
> }
> doit(Mo6MONO,POSTHHMONO,data2)
> 
> results of running function:
> Browse[1]> doit(Mo6MONO,POSTHHMONO,data2)
> [1] "Mo6MONO"
> [1] "data2"
> Error during wrapup: $ operator is invalid for atomic vectors
> 
> 
> 
> I have looked at lm, but don't understand the syntax, and have tried to run lm so as to learn the syntax by just don't understand . . . .
> 

Jim has already given an answer to the specific case of of your example, but lm doesn't actually have formals that are passed such values. It accepts formula objects which have a different syntax and evaluation rules. So it was not clear to me that your preamble matched your example.

When I have done what you did I just passed character vectors and used them inside "[[" since that is the equivalent of using "$". You are advised in the help pages not to use $ inside functions. Notice that deparse(substitute(.)) delivers a character vector.

-- 
David.
> HELP
> 
> Thanks 
> John
> 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 ...{{dropped:15}}



More information about the R-help mailing list