Coursera Series-R programming third week-lexical scopes

Source: Internet
Author: User

Complete R Programming third week

This week the homework is a bit around, more through a cache inverse matrix case, to us to demonstrate the effect of "lexical scope Lexical scopping". But the functions given in the homework are a bit around the mouth, it cost us a lot of thought.

Lexical scopping:

The value of free variables is searched for in the environment where the function is defined.

So

make.power<-function (n) {        pow<-function (x) {                x^n        }}
View Code

For the appeal function, Make.power (3) generates a new function instead of a numeric value. Resulting

Cube<-make.power (3) square<-make.power (2) cube (3)  --->square (3)  ---->9

Make.power (3) generates a x^3 function, and make.power (2) generates a x^2 function. The n here will only look for the value in the scope of the function definition and will not go beyond the function to find it. The parent environment of the built-in function is the function that defines the function itself.

According to the teacher, the lexical scope of such a child is also suitable for more trendy functions such as python. Or will become the mainstream of the future programming community. (compared with dynamic scoping), but one problem is ... Based on complex environment Ah, and so on, these are generally in the physical memory, the memory dependence is very high.

As mentioned here, for these complex winding-around scopes, a relatively simple approach is:

is (Environment (Cube))>- N, pow (two objects inside environment) get ("n", Environment (cube) can see that n is defined as 3

The above two functions can view the environment call object. Suitable for inspection.

Also attached to this assignment, the teacher gave a demonstration example, as well as my personal add notes

Makevector<-function (x=Numeric ()) {m<-null#assign m to nullset<-function (y) {x<<-y#after set (y), the X=y,m=nullm<<-NULL} Get<-function () x#assign X to getSetmean<-function (mean) M<<-mean#here is the mean, but still doubtful, why here to use function (mean). Or in this function, do not do mean related operations, the real solve really cachemean execution? Getmean<-function () m#This copies the M to Getmean (NULL)List (set=set,get=GET, Setmean=Setmean, Getmean=Getmean)} Cachemean<-function (x, ...) {m<-x$getmean ()#first assign the Getmean to M, and if M is not NULL, the following hint pops up        if(! is. Null (M)) {Message ("Getting cached data")                return(M)}#Cache value appearsData<-x$get ()#assigns the first numberic vector to the datam<-mean (data, ...) X$setmean (m) cache M-m}

Above

In addition, several useful functions were also discussed this week

Lapply (to list)

Sapply (lapply simplified version, if the list is a single value, you can output vector vectors, if the length can be output matrix, if different lengths, output list)

Apply (for arrays, that is, matrices of numbers, etc., compared to the for, the field is less, the code is more concise, for example, apply (Array,margin,fun), the margin,1 is a row row,2 columns column

It is said that rowsums, Rowmeans,colsums,colmeans more efficient, not specifically tried

Mapply (Generate list is convenient), such as the following two lines of code, the efficiency of the same, suitable for a fun to apply to different parameters

Mapply (rep,1:4,4:1) List (Rep (1,4), Rep (2,3), Rep (3,2), Rep (4,1))

Tapply (used to loop a subset of vectors, grouped by factors)

Split (group x by factor vector)

Library (Datasets) data (IRIS)#Exploratory Analysisnames (Iris) head (IRIS)#The following attempts to take Virginica,speal. The method of length is all wrongiris[,2]iris[iris$species=="virginica", 2]mean (iris[iris$species=="virginica", 2])##the above is Error,not correct##tapply (Test$sepal.length,test$species,mean)#using Species.mean to group vectors, this method is feasible, but the above method is necessary to look at the error
Library (Datasets) data (Mtcars) #以下为做某个题时的若干测试. And a trial-and-error link. Lapply, the use of Tapply,split, and [[1]] how to use#count mpg via cyld<-tapply (Mtcars$mpg,mtcars$cyl,mean)#split out the Mtcars, get a listSplit (mtcars,mtcars$cyl)#get every mtcars meanlapply (Mtcars,mean)#error in the match fun. (fun), mtcars$cyl should is numberic or chartersapply (Mtcars,mtcars$cyl,mean)##test 4###The below is uncorrect##for tapply out vectors, use [[1]] to take a valueD[[1]]-d[[3]]library (Datasets) head (mtcars) MTCARSD<-tapply (mtcars$hp,mtcars$cyl,mean) d[[1]]-D[[3]]

Above end

Overall sentiment, although Mooc to JHU of Coursera class mixed, but listen carefully, than self-reading to easy to get started.

And programming this kind of thing, must write more, communicate more, can obtain the benefit.

Come on!

Coursera Series-R programming third week-lexical scopes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.