[R] Call to a function

Steven Yen syen04 at gmail.com
Tue Jun 23 23:39:37 CEST 2015


Dear Members
I have a data frame as generated below. I like to be able to call a
function both with a vector and a vector (mydata$v1) in that data frame
(v1). The first call works, but the second does not. Can someone help me
with the second call? Thanks!!

---
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

---
Printout with error message

> mydata<-data.frame(matrix(1:20,ncol=2))
> colnames(mydata) <-c("v1","v2")
> summary(mydata)
        v1              v2
  Min.   : 1.00   Min.   :11.00
  1st Qu.: 3.25   1st Qu.:13.25
  Median : 5.50   Median :15.50
  Mean   : 5.50   Mean   :15.50
  3rd Qu.: 7.75   3rd Qu.:17.75
  Max.   :10.00   Max.   :20.00
>
> aaa<-function(data,w=w){
+   if(is.vector(w)){
+     out<-mean(w)
+   } else {
+     out<-mean(data[wt])
+   }
+ return(out)
+ }
> aaa(mydata,mydata$v1)
[1] 5.5
> aaa(mydata,"v1")
[1] NA
Warning message:
In mean.default(w) : argument is not numeric or logical: returning NA
>



More information about the R-help mailing list