Data frames can be subscripted with
strings directly:
> theData
<- data.frame(aa=c(1,2,3),bb=c(4,5,6),cc=c(7,10,11))
> myMean <-
function(df, var) { mean(df[,var]) }
>
myMean(theData,"aa")
[1] 2
>
myMean(theData,"bb")
[1] 5
>
myMean(theData,"cc")
[1] 9.333333
>
Alan Hochberg
VP, Research
ProSanos Corporation
225 Market St. Ste. 502,
Harrisburg, PA 17101
Tel
717-635-2124 * Fax 717-635-2575
This
message contains ProSanos Corporation information which is confidential and/or
privileged. If you are not the intended recipient, please advise the sender
immediately by reply e-mail and delete this message and any attachments without
retaining a copy. If you are the intended recipient, please protect this information
accordingly.
From:
s-news-owner@lists.biostat.wustl.edu
[mailto:s-news-owner@lists.biostat.wustl.edu] On
Behalf Of David L Lorenz
Sent: Tuesday, December 16, 2008
8:57 AM
To: mandans_p@yahoo.com
Cc:
s-news@lists.biostat.wustl.edu; s-news-owner@lists.biostat.wustl.edu
Subject: Re: [S] Function with
dataframe argument variables.?
There may be some elegant way to do this, but
this will work. The idea is to convert the name in Variable1 to a character
string.
Dave
VarianceT1
<- function(Data, Variable1) {
Variable1
<- deparse(substitute(Variable1))
return(mean(Data[[Variable1]]))
}
|
Mandans <mandans_p@yahoo.com>
Sent
by: s-news-owner@lists.biostat.wustl.edu
12/15/2008 05:39 PM
|
Please
respond to
mandans_p@yahoo.com
|
|
|
To
|
s-news@lists.biostat.wustl.edu
|
|
cc
|
|
|
Subject
|
[S] Function with dataframe argument
variables.?
|
|
Hi
Everyone,
I have quick question regarding writing a function
for a dataframe with arguments called from the dataframe name.
Here is what I am trying to get a simple mean. my
question how do address the Data$Variable1 with an argument Variable passed
into the function.?
-------------------------------
VarianceT1 <- function(Data, Variable1) {
if(!is.data.frame(Data))
stop("Data should be a
dataframe")
if(dim(Data)[1] !=
length(Data$Variable1))
stop("Data and Variable1 should
be of the same length")
a1 <- mean(Data$Variable1)
return(a1)
}
--------------------------------
Appreciate all your help and thanks for all shared
ideas out there on s-news archive.
Thanks a bunch.
Thanks
--------------------------------------------------------------------
This message was distributed by
s-news@lists.biostat.wustl.edu. To
unsubscribe send e-mail to
s-news-request@lists.biostat.wustl.edu with
the BODY of the message: unsubscribe s-news