/Intro-R

Introdução ao R - POO, Métodos, Classes e comparações com outras linguagens

Primary LanguageCSS

Introdução à Linguagem R - Instalação

0 - Instalação

Servidores locais:

./img/CRAN.png

IDEs: RStudio, VSCode, Emacs

RStudio

Linux (Ubuntu)

sudo apt install -f ~/Downloads/rstudio-2023.09.1-494-amd64.deb

Windows

Abrir executável

C:\Downloads\rstudio-2023.09.1-494.exe

VSCode

In VS Code Quick Open (Ctrl+P):

ext install REditorSupport.r

Emacs

  • ess
  • ess-R-data-view
  • polymode
  • poly-R
  • company-stan
  • eldoc-stan
  • flycheck-stan
  • stan-mode
(use-package ess)
(use-package ess-R-data-view)
(use-package polymode)
(use-package poly-R)
(use-package company-stan)
(use-package eldoc-stan)
(use-package flycheck-stan)
(use-package stan-mode)

1 - A língua

R is a dynamic language for statistical computing that combines lazy functional features and object-oriented programming.

This rather unlikely linguistic cocktail would probably never have been prepared by computer scientists, yet the language has become surprisingly popular.

Resumo da Ópera

  • Tipação fraca.
  • O.O. suporta tipação.
  • Escopação léxica dinâmica.
  • Aspectos Funcionais, como lazy loading, pipping e maps.
  • Linguagem interpretada (vai bem em scripts).
  • Rápida
    • Utiliza línguas low-level, C, Fortran under the hood.
  • Suporta imperatividade.

Tipação Dinâmica

Exemplo 1 - Imperativa

Rotinas Imperativas

weight <- 85
size <- 1.84
(BMI <- weight/size^2)

Exemplo 2 - Orientação a Objeto

### Definition of an object BMI
setClass("BMI", representation(weight="numeric", size="numeric"))
setMethod("show", "BMI",
 function(object){cat("BMI =",object@weight/(object@size^2)," \n ")}
 )
### Creation of an object for me, and posting of my BMI
(myBMI <- new("BMI",weight=85,size=1.84))

### Creation of an object for her, and posting of her BMI
(herBMI <- new("BMI",weight=62,size=1.60))

Exemplo 2 - OOP and Typechecking

### Traditional programming, no type
(weight <- "Hello")

## Using classes
 new("BMI",weight="Hello",size=1.84)

Exemplo 4 - Semelhanças com outras linguagens

Objetos com métodos implícitos, como ___init___, em Python:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

print(p1.name)
print(p1.age)

Exemplo 5 - Semelhanças com outras linguagens

(let [person {:name "John" :age 36}]
      ;; supérfulo criar um alias:
      ;; p1 person
  (do
    (println (:name person))
    (println (:age person))))

;; (f x y)
;; (let binds body)
;; (+ 1 2)

(let [person {:name "John" :age 36}
      show (fn [obj] (str (:name obj) " " (:age obj)))]
      ;; supérfulo criar um alias:
      ;; p1 person
    ;; (:name person)
    ;; (:age person))
  (show person))

Exemplo 6 - Semelhanças com outras linguagens

package main

import (
	"fmt"
	"strconv"
)

type Person struct {
	name string
	age  int
}

func (p Person) show() string {
	return p.name + " " + strconv.Itoa(p.age)
}

func main() {

	//creating struct specifying field names
	p1 := Person{
		name: "Fulano",
		age: 20,
	}

	//creating struct without specifying field names
	p2 := Person{"Ciclano", 37}

    // "show" method
	fmt.Println(p1.show())
	fmt.Println(p2.show())
}

Escopação Léxica Dinâmica

Some languages, like Perl and Common Lisp, allow the programmer to choose static or dynamic scope when defining or redefining a variable.

Examples of languages that use dynamic scope include Logo, Emacs Lisp, LaTeX and the shell languages bash, dash, and PowerShell.

Let - raízes do conceito de escopo léxico dinâmico

Exemplo 1, let

  • Local Escoping
(let ((a 1)
      (b 2))
    (+ a b))
  • Implicit Local Escoping
(defun f (a b)
  (+ a b))

(f 1 2)

Exemplo 2, Common Lisp

(defclass book ()
  ((title :reader title
          :initarg :title)
   (author :reader author
           :initarg :author))
  (:documentation "Describes a book."))

(defmethod show ((b1 book))
  (let ((titulo (title b1))
        (autor (author b1))) 
   (print (format T "~S, ~S" titulo autor))))

(defparameter b1 (make-instance 'book
                        :title "ANSI Common Lisp"
                        :author "Paul Graham"))
(show b1)

Exemplo 3, R: Classes e Métodos

require(grDevices)
setClass(
 Class="Trajectories",
 representation=representation(
 times = "numeric",
 traj = "matrix"
 )
)
setMethod(
  f= "plot",
  signature= "Trajectories",
  definition=function (x,y,...){
    matplot(x=x@times,
            y=t(x@traj), ## (x, y) coordenates
            xaxt="n",
            type="l",
            ylab= "",
            xlab="",
            pch=1 ## plot specification
           )
    axis(1,at=x@times)
  }
)

Exemplo 3, R: R em ação

trajPitie <- new(Class="Trajectories")
trajCochin <- new(
  Class= "Trajectories",
  times=c(1,3,4,5),
  traj=rbind (
    c(15,15.1, 15.2, 15.2),
    c(16,15.9, 16,16.4),
    c(15.2, NA, 15.3, 15.3),
    c(15.7, 15.6, 15.8, 16)
  )
)

trajStAnne <- new(
  Class= "Trajectories",
  times=c(1: 10, (6: 16) *2),
  traj=rbind(
    matrix (seq (16,19, length=21), ncol=21, nrow=50, byrow=TRUE),
    matrix (seq (15.8, 18, length=21), ncol=21, nrow=30, byrow=TRUE)
  )+rnorm(21*80,0,0.2)
)
par(mfrow=c (1,2))
plot(trajCochin)
plot(trajStAnne)

2 - Scripting powers

R é uma linguagem interpretada.

Nome do arquivo: r-script

#!/usr/bin/r

require(grDevices)
options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)
print(args)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandArgs(trailingOnly=FALSE))

start_date <- as.Date(args[1])
name <- args[2]
n <- as.integer(args[3])
rm(args)

# Some computations:
x <- rnorm(n)
png(paste(name,".png",sep=""))
plot(start_date+(1L:n), x)
dev.off()

summary(x)
Rscript $(command -v r-script) 2023-01-01 "Deltrano" 30

Resultado

Deltrano.png

3 - Jupyter, a tríade Julia, Python, R

STRT Links

R:

STRT Reveal.js Options