[R] Why eval(parse(text="var(vec)")) return a matrix but NOT a number?

Charles C. Berry cberry at tajo.ucsd.edu
Wed Mar 17 17:09:40 CET 2010


On Wed, 17 Mar 2010, Yong Wang wrote:

> Dear List
>
> I am getting a problem when using "eval(parse)".
> Code below sketchs what I am trying to do:
>
> For each row of a N*K dataframe (I use a 2*2 dataframe in the example below),
> applying a number of functions and get the outputs (two functions,
> "sum" and "var" are used in the example below).
>
> The problem is  eval(parse(text="sum(para)")) works fine but not when
> "sum" is replaced by "var".
> in the later case, a matrix instead of a number is returned.
>
> Any suggestion highly appreciated.
>
> Thank you
>
> #===================================================The function
> myloop	<-function(datfra,funs)	{
>
> 		rows<-dim(datfra)[1];
> 		totfunnum<-length(funs);
>
> 			for (i in 1:rows) 	{
> 			vec<-datfra[i,];
# I suggest:
 			browser()
# Now try print(vec), str(vec), etc till you understand
#    why the results do not agree with your expectation

# HTH,
# Chuck
>
> 				for(k in 1:totfunnum)	{
> 				print(funs[k]);
> 				x<-eval(parse(text=funs[k]));
> 				print(x);
> 							}
>
> 						}
> 				}
>
>
> #================================================Experiemental run
> workport<-data.frame(matrix(1:4,2,2))
> funs<-c("sum(vec,na.rm=T)","var(vec,na.rm=T)")
> myloop(workport,funs)
>
> #================================================ Outputs of the
> Experimental run
>
> [1] "sum(vec,na.rm=T)"
> [1] 4
> [1] "var(vec,na.rm=T)"
>   X1 X2
> X1 NA NA
> X2 NA NA
> [1] "sum(vec,na.rm=T)"
> [1] 6
> [1] "var(vec,na.rm=T)"
>   X1 X2
> X1 NA NA
> X2 NA NA
>
> ______________________________________________
> 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.
>

Charles C. Berry                            (858) 534-2098
                                             Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu	            UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/  La Jolla, San Diego 92093-0901



More information about the R-help mailing list