美文网首页R语言学习笔记
R语言学习笔记7-程序结构篇

R语言学习笔记7-程序结构篇

作者: RudyHe | 来源:发表于2015-12-05 00:02 被阅读69次
    - Basic
        - u<-matrix(c(1,2,3,1,2,4),nrow=3)
        - v<-matrix(c(8,12,20,15,10,2),nrow=3)
        - for (m in c("u","v")) {
            - z<-get(m)
            - print(lm(z[,2]~z[,1]))
        - }
        - y<-if(x==2) x else x+1
        - x%/%y    # integer divide
        - x%%y    # mod
        - x&y    # vector and
        - x|y    # vector or
        - |x    # not
        - oddcount<-function(x) {
            - k<-0
            - k    # as return val
        - }
        - g<-function() {
            - t<-function(x) return(x^2)
            - return(t)
        - }
        - ls()    # show current environment variable
        - x<-c(13,5,12)
        - sort(x)    # 5 12 13
        - x    # not changed x
            - 13 5 12
        - x<-sort(x)    # 5 12 13
        - oddsevens<-function(v) {
            - odds<-which(v%%2==1)
            - evens<-which(v%%2==1)
            - list(o=odds,e=evens)    # return multiple values
        - }
        - # global variable
        - f<-function() {
            - x<<-...
            - y<<-...
        - }
        - x<-...
        - y<-...
        - f()    # x,y are changed in f
        - ...<-x
        - ...<-y    # use new x,y
        - # clojure
        - counter<-function() {
            - ctr<-0
            - f<-function() {
                - ctr<<-ctr+1
                - cat("sentence",ctr,"\n")
            - }
            - return(f)
        - }
        - c1<-counter()
        - c2<-counter()
        - c1()    # ctr=1
        - c1()    # ctr=2
        - c2()    # ctr=1
        - c2()    # ctr=2
        - # recursion
        - quicksort<-function(x) {
            - if (length(x)<=1) return(x)    # end condition
            - pivot<-x[1]
            - therest<-x[-1]
            - sv1<-therest[therest<pivot]
            - sv2<-therest[therest>=pivot]
            - sv1<-quicksort(sv1)
            - sv2<-quicksort(sv2)
            - return(c(sv1,pivot,sv2))
        - }
        - "%a2b%"<-function(a,b) return(a+2*b)    # custom operator
        - 3 %a2b% 5
        - y<-apply(z,1,function(x) x/c(2,8))    # anonymous function
    

    相关文章

      网友评论

        本文标题:R语言学习笔记7-程序结构篇

        本文链接:https://www.haomeiwen.com/subject/jkishttx.html