--- loncom/homework/templates/Rnumerical.problem 2009/04/18 23:43:54 1.1 +++ loncom/homework/templates/Rnumerical.problem 2009/06/23 03:01:20 1.2 @@ -5,20 +5,21 @@ $n=&random(15,25,1); $offset=&random(2,5,0.1); $slope=&random(0.6,2.5,0.1); # construct a data set using R -$data=&cas('R',"set.seed($seed);x<-1:$n;w<-1+sqrt(x)/2;data.frame(x=x,y=$offset+$slope*x+rnorm(x)*w);"); -# separate into an x and a y vector -@datatable=split(/\s+/gs,$data); -for ($i=0;$i<2*$n;$i+=2) { - push(@x,$datatable[$i]); - push(@y,$datatable[$i+1]); -} +# dump is for debugging, print to screen to see data structure +($data,$dump)=&cas_hashref('R',"set.seed($seed);x<-1:$n;w<-1+sqrt(x)/2;data.frame(x=x,y=$offset+$slope*x+rnorm(x)*w);"); +@x=&cas_hashref_array($data,'x'); +@y=&cas_hashref_array($data,'y'); $datax=join(',',@x); $datay=join(',',@y); # calculate the right answer using R -($intercept,$slope)=split(/\s+/,&cas('R',"x<-c($datax);y<-c($datay);dataset<-data.frame(x=x,y=y);fm<-lm(y~x,data=dataset);array(coef(fm),dim=2);")); -$answer="$slope*x+$intercept"; +($answerdata,$dump)=&cas_hashref('R',"x<-c($datax);y<-c($datay);dataset<-data.frame(x=x,y=y);fm<-lm(y~x,data=dataset);"); +$answer=&cas_hashref_entry($answerdata,'coefficients','x').'*x+'.&cas_hashref_entry($answerdata,'coefficients','(Intercept)'); - + + +Consider the plotted data set.
+ + @x @y @@ -27,13 +28,11 @@ $answer="$slope*x+$intercept"; -Consider the data set -
$data
- +
Give a linear function approximating the data.
y(x)= - +