[R] Passing a data frame or matrix and working with a column of the data frame or matrix

John Sorkin jsorkin at grecc.umaryland.edu
Fri Dec 24 22:29:53 CET 2010


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 th...{{dropped:6}}



More information about the R-help mailing list