[R] Call to a function

David Winsemius dwinsemius at comcast.net
Wed Jun 24 08:50:39 CEST 2015


On Jun 23, 2015, at 3:20 PM, boB Rudis wrote:

> You can do something like:
> 
> aaa <- function(data, w=w) {
>  if (class(w) %in% c("integer", "numeric", "double")) {

I think you will find that inherits(w, "numeric") is more compact and safer. Both "integer" and "double" do inherit from "numeric" (and "double" is equivalent to "numeric")

The test for 'is.vector' is also going to produce some surprises. List-objects may pass that test:

> sum( list(1,2,3))
Error in sum(list(1, 2, 3)) : invalid 'type' (list) of argument

> is.vector( list(1,2,3))
[1] TRUE


> x=1:4
> attr(x, "some_attr") <- "something"
> is.vector(x)
[1] FALSE


-- 
David.
>    out <- mean(w)
>  } else {
>    out <- mean(data[, w])
>  }
>  return(out)
> }
> 
> (there are some typos in your function you may want to double check, too)
> 
> On Tue, Jun 23, 2015 at 5:39 PM, Steven Yen <syen04 at gmail.com> wrote:
>> mydata<-data.frame(matrix(1:20,ncol=2))
>> colnames(mydata) <-c("v1","v2")
>> summary(mydata)
>> 
>> aaa<-function(data,w=w){
>>  if(is.vector(w)){
>>    out<-mean(w)
>>  } else {
>>    out<-mean(data[wt])
>>  }
>> return(out)
>> }
>> 
>> aaa(mydata,mydata$v1)
>> aaa(mydata,"v1")      # want this call to work
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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
Alameda, CA, USA



More information about the R-help mailing list