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

Yong Wang wangyong1 at gmail.com
Wed Mar 17 09:04:01 CET 2010


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,];

				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



More information about the R-help mailing list