Hi: David explained the quoting issue well. My question is: what type of output do you want from the function? Using David's fix, I get
learnfn <- function(data,column) { print(data) data[, column] } The idea is to leave the column unquoted in the body of the function and to quote it in the function call, as in learnfn(data, 'x') x y z 1 1 0.6651562 11 2 2 2.9268958 12 3 3 3.9521160 13 4 4 4.6214315 14 5 5 7.4039838 15 6 6 5.7174185 16 7 7 7.7249067 17 8 8 6.9924741 18 9 9 7.4228238 19 10 10 9.4208857 20 [1] 1 2 3 4 5 6 7 8 9 10 After printing the data frame, the return value is a vector. I would expect that one might prefer a data frame instead. If so, you need to modify the return to learnfn <- function(data,column) { print(data) data[, column, drop = FALSE] } > learnfn(data, 'x') x y z 1 1 0.6651562 11 2 2 2.9268958 12 3 3 3.9521160 13 4 4 4.6214315 14 5 5 7.4039838 15 6 6 5.7174185 16 7 7 7.7249067 17 8 8 6.9924741 18 9 9 7.4228238 19 10 10 9.4208857 20 x 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 On Fri, Dec 24, 2010 at 1:29 PM, John Sorkin <jsor...@grecc.umaryland.edu>wrote: > I am trying to learn more about how to write functions. I would like to > pass a data frame (or matrix) and depending on the parameters passed to the > function work with a given column of the data frame or matrix. My function, > learnfn is given below as are two calls to the function. The first call is > an attempt to print the x column from the data frame, the second call is an > attempt to print the y column. I hope someone can modify my function so it > works. > Thank you, > John > > # create data frame > x<-1:10 > y <- x+rnorm(10) > z <- 11:20 > data <- data.frame(x,y,z) > data > > > learnfn <- function(data,column) { > print(data) > data[,"column"] > } > > # work on the "x" column > learnfn(data,x) > > # work on the "y" column > learnfn(data,y) > > > John David Sorkin M.D., Ph.D. > Chief, Biostatistics and Informatics > University of Maryland School of Medicine Division of Gerontology > 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:13}} ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.