[R] Trying to understand the magic of lm (Still trying)
Sorkin, John
j@ork|n @end|ng |rom @om@um@ry|@nd@edu
Fri May 10 21:53:32 CEST 2019
A number of people have helped me in my mission to understand how lm (and other fucntions) are able to pass a dataframe and then refer to a specific column in the dataframe. I thank everyone who has responded. I now know a bit about deparse(substitute(xx)), but I still don't fully understand how it works. The program below attempts to print a column of a dataframe from a function whose parameters include the dataframe (df) and the column requested (col). The program works fine until the last print statement were I receive an error, Error in `[.data.frame`(df, , col) : object 'y' not found . I hope someone can explain to me (1) why my code does not work, and (2) what I can do to fix it.
Many thanks to everyone who tries to help lost souls like me!
Thank you,
John
data <- data.frame(x=c(1,2,3,4,5),y=c(5,4,3,2,1))
data
doit <- function(df,col){
dfx <- deparse(substitute(df))
colx<- deparse(substitute(col))
cat("results of deparse substitute")
print(colx)
print (dfx)
cat("I can print the columns using column relative reference\n")
print(df[,1])
print(df[,2])
cat("I can print the entire data frame \n")
print(df)
cat("I can print a single columng from the dataframe using a column name\n")
print(df[,col])
}
doit(data,y)
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)
[[alternative HTML version deleted]]
More information about the R-help
mailing list