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

Jim Lemon drjimlemon at gmail.com
Tue Oct 13 00:35:22 CEST 2015


Hi John,
Here are a couple of ways to do this. Note that they produce slightly
different results.

data2<-data.frame(POSTHHMONO=c(1,2,3,4),Mo6MON=c(10,11,12,13))
doit<- function(pre,post,data) {
  element <- deparse(substitute(pre))
  print(element)
  print(data[element])
  frame<-deparse(substitute(post))
  print(frame)
  print(data[frame])
}
doit(Mo6MON,POSTHHMONO,data2)

# this produces the same as the $ extractor
doit<- function(pre,post,data) {
  element <- deparse(substitute(pre))
  print(element)
  print(data[,element])
  frame<-deparse(substitute(post))
  print(frame)
  print(data[,frame])
}
doit(Mo6MON,POSTHHMONO,data2)

Jim



On Tue, Oct 13, 2015 at 9:11 AM, John Sorkin <jsorkin at grecc.umaryland.edu>
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 . . . .
>
> 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:16}}



More information about the R-help mailing list