[R] Passing a data frame or matrix and working with a column of the data frame or matrix
David Winsemius
dwinsemius at comcast.net
Fri Dec 24 22:48:13 CET 2010
On Dec 24, 2010, at 4:29 PM, John Sorkin 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"] # there is no column named "column"
# Try:
data[column] # or
data[[column]]
# the column object will have a character value and either "[" or "[["
will evaluate an unquoted argument.
> }
>
> # work on the "x" column
> learnfn(data,x)
# and there is no x ... well there is, but if you passed a vector
that evaluated to 1:10 to "[" you would be asking for the first 10
columns, and "[[" would throw an error.
# Try:
learnfn(data, "x")
You seem to be reversing the expected conventions of quoting or not-
quoting. When you invoke a function you need to send it a specific
value but when you are writing the function you need to leave values
open.
--
David.
>
> # 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 th...{{dropped:
> 6}}
>
> ______________________________________________
> R-help at 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.
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list