"
Для задания No 4 из Лабораторной работы No 2 написать программы
в которых Пользователь с клавиатуры вводит значения двух переменных разных типов,
которые затем сравниваются между собой. Использовать функции readline(), print(
и функции преобразования типов.
"
{
  a1 <- as.integer(readline("Введите число №1 -> "))
  a2 <- as.double(readline("Введите число №2 -> "))

  print(paste("Тип числа №1:", typeof(a1)))
  print(paste("Тип числа №2:", typeof(a2)))

  if (a1 < a2) {
    print("Число №1 больше")
  } else{
    print("Число №2 больше")
  }
}


#!/usr/bin/Rscript

# Bhishan Poudel
# Jan 8, 2016

# clear; Rscript ifElse.r

# if else example1
x <- -5
if(x > 0){
  print("Non-negative number")
  } else {
    print("Negative number")
}

# single line example
x <- 5
if(x > 0) print("Non-negative number") else print("Negative number")

# nested if...else statement
x <- 0
if (x < 0) {
  print("Negative number")
} else if (x > 0) {
  print("Positive number")
} else
  print("Zero")

cat("\nexample 3\n")
# example 3
##=================
x <- 6
#x <- 4
if (x < 10){
  if(x < 5) {
    print("The number is less than 5")
  } else {
    print("The number is in between 5 and 10")
  }
}

###################################################


# if only
x <- 2

if (x > 5){
  print('x is greater than 5')
}

x <- 7

if (x > 5){
  print('x is greater than 5')
}

# if + else
x <- 4

if (x > 5){
  print('x is greater than 5')
} else {
  print('x is less than 5')
}

x <- 7

if (x > 5){
  print('x is greater than 5')
} else {
  print('x is less than 5')
}

x < - 5  # single line example
y <- if(x >= 0) 5 else 6
y

# if + else if + else
x <- 5

if (x > 5){
  print('x is greater than 5')
} else if (x == 5) {
  print('x is 5')
} else {
  print('x is less than 5')
}

# the first if / else if / else that is TRUE will execute, ending the if statement
x <- 1

if (x > 5){
  print('x is greater than 5')
} else if (x == 1) {
  print('x is 1')
} else if (x == 5) {
  print('x is 5')
} else {
  print('x is less than 5')
}

if (x > 5){
  print('x is greater than 5')
} else if (x != 5) {
  print('x is not 5')
} else if (x == 5) {
  print('x is 5')
} else {
  print('x is less than 5')
}


# The goal of files, like this one, is to introduce you to the
# R programming language. Let's start with by unraveling a
# little mystery!

# 1. Run the code below to create the vector 'udacious'.
# You need to highlight all of the lines of the code and then
# run it. You should see "udacious" appear in the workspace.

udacious <- c("Chris Saden", "Lauren Castellano",
              "Sarah Spikes","Dean Eckles",
              "Andy Brown", "Moira Burke",
              "Kunal Chawla")

# You should see something like "chr[1:7]" in the 'Environment'
# or 'Workspace' tab. This is because you created a vector with
# 7 names that have a type of character (strings). The arrow-like
# '<-' symbol is the assignment operator in R, similar to the
# equal sign '=' in other programming languages. The c() is a
# generic function that combines arguments, in this case the
# names of people, to form a vector.

# A vector is one of the data types in R. Vectors must contain
# the same type of data, that is the entries must all be of the
# same type: character, logical (TRUE or FALSE), or numeric.

# HELPFUL TIP: You can add values to a vector.
# Run each line of code one at a time below to see what is happening.

numbers <- c(1:10)

numbers

numbers <- c(numbers, 11:20)

numbers

# 2. Replace YOUR_NAME with your actual name in the vector
# 'udacious' and run the code. Be sure to use quotes around it.

udacious <- c("Chris Saden", "Lauren Castellano",
              "Sarah Spikes","Dean Eckles",
              "Andy Brown", "Moira Burke",
              "Kunal Chawla", "Steve Tan")

# Notice how R updates 'udacious' in the workspace.
# It should now say something like 'chr[1:8]'.

# 3. Run the following two lines of code. You can highlight both lines
# of code and run them.

mystery = nchar(udacious)
mystery

# You just created a new vector called mystery. What do you
# think is in this vector? (scroll down for the answer)

# Mystery is a vector that contains the number of characters
# for each of the names in udacious, including your name.

# 4. Run this next line of code.

mystery == 11

# Here we get a logical (or boolean) vector that tells us
# at what locations or indices in the vector where the number
# of characters for the name is equal to 11.

# 5. Let's use this boolean vector, mystery, to subset our
# udacious vector. What do you think the result will be when
# running the line of code below?

# Think about the output before you run this next line of code.

udacious[mystery == 11]

# Scroll down for the answer

# It's your Udacious Instructors for the course!
# (and you may be in the output if you're lucky enough
# to have 11 characters in YOUR_NAME) Either way, we
# think you're pretty udacious for taking this course.

# 6. Alright, all mystery aside...let's dive into some data! Run
# this next command to load the mtcars data.

data(mtcars)

# You should see mtcars appear in the 'Environment' tab.
# R has stored the mtcars data into a spreadsheet-like object
# called a data frame. Run the next command to see what variables
# are in the data set.

names(mtcars)

# names(mtcars) should output all the variable
# names in the data set. You might notice that the car names
# are not a variable in the data set. The car names have been saved
# as row names. More on this later.

# You should also see how many observations (obs.) are in the
# the data frame and the number of variables on each observation.

# 7. To get more information on the data set and the variables
# run the this next line of code.

?mtcars

# You can type a '?' before any command or a data set to learn
# more about it. The details and documentation will appear in
# the 'Help' tab.

# 8. To print out the data, run this next line as code.

mtcars

# Scroll up and down in the console to check out the data.
# This is the entire data frame printed out.

# 9. Run these next two functions, one at a time,
# and see if you can figure out what they do.

str(mtcars)

dim(mtcars)

# Scroll down for the answer.

# The first command, str(mtcars), gives us the structure of the
# data frame. It lists the variable names, the type of each variable
# (all of these variables are numerics) and some values for each
# variable.

# The second command, dim(mtcars), should output '[1] 32 11'
# to the console. Don't worry about the [1].
# I'll explain that later.

# 10. Read the documentation for row.names if you're want to know more.
?row.names

# Run this code to change the row names of the cars to numbers.
row.names(mtcars) <- c(1:32)

# Now print out the data frame by running the code below.
mtcars

# It's tedious to relabel our data frame with the right car names
# so let's reload the data set and print out the first ten rows.

data(mtcars)
head(mtcars, 10)

# The head() fucntion prints out the first six rows of a data frame
# by default. Run the code below to see.
head(mtcars)

# I think you'll know what this does.
tail(mtcars, 3)

# 11. We've run nine commands so far:
#      c, nchar, data, str, dim, names, row.names, head, and tail.

# All of these commands took some inputs or arguments.
# To determine if a command takes more arguments or to learn
# about any default settings, you can look up the documentation
# using '?' before the command, much like you did to learn about
# the mtcars data set and the row.names

# 12. Let's examine our car data more closely. We can access an
# an individual variable (or column) from the data frame using
# the '$' sign. Run the code below to print out the variable
# miles per gallon. This is the mpg column in the data frame.

mtcars$mpg

# Print out any two other variables to the console.

# This is a vector containing the mpg (miles per gallon) of
# the 32 cars. Run this next line of code to get the average mpg for
# for all the cars. What is it?

# Enter this number for the quiz on the Udacity website.
# https://www.udacity.com/course/viewer#!/c-ud651/l-729069797/e-804129314/m-830829287

mean(mtcars$mpg)


#' ---
#' title: "Uvod u R"
#' author:
#'    - "Milutin Pejovic, Petar Bursac"
#' date: "`r format(Sys.time(), '%d %B %Y')`"
#' output:
#'    html_document:
#'      keep_md: true
#'      theme: "simplex"
#'      highlight: tango
#'      toc: true
#'      toc_depth: 5
#'      toc_float: true
#'      fig_caption: yes
#' ---
#'
#' # Strukture podataka
#'
#' Podsetićemo se na početku osnovnih struktura podataka u R-u
#'
#+ echo = FALSE, warning = FALSE, message = FALSE, fig.width = 10, fig.height = 8, fig.align='center'
knitr::include_graphics("Figures/strukture_podataka.jpg")
#'
#' # Osnovni tipovi i klase podataka u R-u
#'
#'
#'
#' ## Atomic vectors
#'

v1 <- c(1, 2, 3, 4, 5, 6)

v2 <- 1:6

is.vector(v1)

#' ### Tipovi podatka
#'
#' R razlikuje šest osnovnih tipova podatka, a to su *doubles, integers, characters, logicals, complex, and raw*. Tip podatka je obično poznat autoru koda, međutim ukoliko ima potrebe da se sazna kojeg je tipa određeni podatak skladišten u nekom vektoru, to moguće saznati pozivom komandom `typeof`:
#'
#' #### Double
#'
typeof(v1)
#'
#' #### Integer
#'
v3 <- c(1L, 2L, 3L, 4L, 5L, 6L)

typeof(v3)

#'
#' #### Characters
#'
v4 <- c("Milutin", "Vojkan", "Petar")

typeof(v4)

prof_name <- paste("Milutin", "Pejovic", sep = " ")

prof_name

v5 <- paste(c("Milutin", "Vojkan", "Petar"), "GRF", sep = "_")

typeof(v5)

#'
#'
#' #### Logicals
#'
v6 <-c(TRUE, FALSE, TRUE)

typeof(v6)

v7 <-c(T, F, T)
v7
typeof(v7)

#'
#' #### Nedostajuće vrednosti (`NA`)
#'
#' Nodostajuće ili nepoznate vrednosti u R-u se predstavljaju sa `NA`. Treba imati na umu da nedostajuća vrednost nije nula vrednost, odnosno da bilo koja operacija sa nedostajućom vrednosti rezultira takođe u nedostajuću vrednost.
#'
#+ include = TRUE

1 > 5

NA > 5

10 * NA

#'
#' Izuzeci su samo sledeće operacije:
#'
#+ include = TRUE
NA ^ 0

NA | TRUE # operator | znači "ili"

NA & FALSE
#'
#'
#' #### Provera tipa podataka
#'
#' Provera tipa podataka se može sprovesti pozivanjem neke od funkcija iz familije `is.*()`, kao na primer `is.logical()`, `is.integer()`, `is.double()`, ili `is.character()`. Postoje i funkcije kao što su `is.vector()`, `is.atomic()`, ili `is.numeric()` ali oni ne služe toj svrsi.
#'
#+
is.numeric(v1)

is.integer(v1)

is.logical(v1)
#'
#'
#' #### Prinudna konverzija imeđu tipova podataka
#'
#' Kao što je poznato, vektor, matrica ili array su strukture podataka koje mogu sadržati samo jedan tip podataka. Stim u vezi, ukoliko se u nekom vektoru nađu dva tipa podataka, R će prema integrisanim pravilima (`character → double → integer → logical`) prinudno transformisati tip podataka.
#'
#+ echo = FALSE, warning = FALSE, message = FALSE, fig.width = 10, fig.height = 10, fig.align='center'
knitr::include_graphics("Figures/prinudna_promena.jpg")
#
str(c("a", 1)) # komanda `str` pokazuje strukturu podataka

#'
#' ## Atributi
#'
#' ### `Names` (nazivi)
#'

names(v1) <-c("jedan", "dva", "tri", "cetiri", "pet", "sest")

v1+1 # Imena ne prepoznaju vrednost na koju se odnose

names(v1) <- NULL # Uklanjanje atributa

#'
#' ### `Dim` (dimenzije)
#'
#' Vektor se moze transformisati u dvo-dimenzionalnu strukturu podataka - matricu, dodavanjem odgovarajućih dimenzija pomoću komande `dim`:
#'
#+ include = TRUE

dim(v1) <- c(2, 3)

v1

#'
#' Na isti način, vektor se može transformisati u `array`:
#'
#+ include = TRUE

v1 <- 1:6
dim(v1) <- c(1, 2, 3)
v1
#'
#'
#'
#'
#' ### Klase podataka
#'
#' Jedan od najvažnijih atributa koji se vezuje za osnovne strukture podataka u R-u je `klasa`, čime se definiše jedan od objektno orijentisanih pristupa definisanja strukture podataka poznat pod imenom `S3` klase. R podržava više sistema za objeknto orijentisano struktuiranje podataka kao što su `S3`, `S4` i `R6`. `S3` je osnovni sistem i podržan je u okviru osnovne istalacije R-a.
#' Dodavanjem atributa `class` R objekat postja `S3` objekat i od toga zavisi kako će se neke osnovne funkcije (`generic functions`) ophoditi prema tom objektu. Drugim rečima, rezultat neke operacije zavisi od klase podataka.
#'
#' U okviru ovog poglavlja, razmotrićemo tri osnovne klase vekorskih podataka:
#'
#' #### `factors`
#'
#' Faktor je vektor koji može sadržati samo određeni broj predefinisanih vrednosti i služi za skladištenje kategoričkih promenljivih. Faktorski vektor u sebi sadrži celobrojne vrednosti kojima je dodeljen naziv, odnosno nivo (`level`). Tako na primer:
#'
v7 <- factor(c("a", "b", "b", "a"))

v7

typeof(v7)

attributes(v7)

#' Faktorski vektor je pogodan za grupisanje podataka, što nam može omogućiti analizu podataka prema grupi kojoj pripadaju.
#'
#'
#' #### `Dates` (Datum) vektori
#'
#' `Dates` ili datumski vektori vektori u sebi sadrže podatak o vremenu na dnevnoj rezoluciji i kreirani su na osnovu `double` vrednosti. Oni predstavljanju broj dana počev od `1970-01-01`
#'
v8 <- Sys.Date()

typeof(v8)

attributes(v8)

as.numeric(v8)

v9 <- as.Date("1983-03-30")
v9

as.numeric(v9)

#'
#' #### `Date-time` (datum-vreme) vektori
#'
#' R podržava dva načina u okviru `S3` klasa za skladištenje informacija o datumu-vremenu POSIXct, and POSIXlt. POSIX je skraćenica od Portable Operating System Interface što je skraćenica za familiju standarda za razmenu informacija o vremenu. `ct` je skraćenica od `calendar`, a `lt` od  `local time`. POSIXct vektor je kreiran na osnovu `double` vektora i predstavlja broj sekundi od `1970-01-01`.
#'

v10 <- as.POSIXct("2020-11-04 10:00", tz = "UTC")

typeof(v10)

attributes(v10)

#'
#'
#'
#' # Podešavanje radnog direktorijuma
#'
#' Ukoliko postoji potreba da se neka skripta veže za određeni set podataka koji se nalazi u određenom folderu, često je potrebno definisati radni direktorijum. Time se praktično definiše `default` putanja koju će koristiti sve funkcije koje za argument koriste putanju do određenog foldera, ukoliko se ne podesi drugačije. Podešavanje radnog direktorijuma se vrši pozivom komande `setwd()`
#'
#?setwd()

#setwd(dir = "C:/R_projects/Nauka_R/Slides")
#'
#' Ukoliko postoji potreba da se proveri koja je aktuelna putanja, odnosno koji je aktuelni radni direktorijum, to se može učiniti pozivom komande `getwd()`.
#'
#getwd()
#'
#' Izlistavanje fajlova koji se nalaze u nekom direktorijumu se vrši pozivom komande `ls()`
#'
#' >
Zadatak 1

#' > + Podesiti radni direktorijum.
#' > + Izlistati sve fajlove koji se nalaze u radnom direktorijumu.
#'
#'Podešavanje radnog direktorijuma je korisno koristiti ako prilikom rada koristimo konstantno jedinstven direktorijum sa skriptama, podacima i drugim potrebnim fajlovima. Tada u radu i korišćenju funkcija možemo koristiti relativne putanje ka pod-fodlerima ako je potrebno, inače se podrazumeva data putanja kao apsolutna.
#'
#'
#' # Učitavanje podataka u R-u
#'
#' Za učitavanje podataka u radno okruženje koriste se funkcije, koje rade na principu zadavanja putanje ka podacima, kao i formata podataka, koji ne mora biti eksplicitno naveden. Neke od osnovnih funkcija su:
#'
#'
#+ include = TRUE
studenti <- read.table(file = "C:/R_projects/Nauka_R/Slides/data/Students_IG1.txt", sep = ",", header = TRUE)

studenti <- read.csv(file = "C:/R_projects/Nauka_R/Slides/data/Students_IG1.txt", header = TRUE, stringsAsFactors = FALSE)
#'
#' ## `readxl` paket
#'
#'Učitavanje excel tabela je moguće učiniti putem paketa "readxl":
#+ eval = FALSE
install.packages("readxl")
library(readxl)

studenti <- readxl::read_xlsx(path = "C:/R_projects/Nauka_R/Slides/data/Students_IG1.xlsx", sheet = "Students")

#'
#'
#'
#' ## Pregled podataka
#'
str(studenti) # Obratite pažnju da su imena studenata skladištena kao faktorske kolone u okviru data.frame?

#' Ukoliko želimo da se određene kolone ne transformišu u faktorske prilikom učitavanja potrebno opciju `stringsAsFactors` podesititi da bude `FALSE`.
#'

class(studenti)

head(studenti, 5)

tail(studenti, 5)

dim(studenti)

#'
#'
#'
#' ## Selektovanje podataka
#'
#' U okviru R-a postoji poseban sistem notacije kojim je moguće pristupiti vrednostima objekta. Kako bi pristupili podatku ili setu podataka (red-u i/ili kolona-ma), koristi se sledeće notacija sa [] zagradama:

# studenti[ , ]

#' U okviru zagrada pišu se dva indeksa odvojena zarezom, pri predstavlja broj **reda** i drugi predstavlja broj **kolone**. Indeksi mogu biti napisani na veći broj načina, i to:
#'
#' - Pozitivne celobrojne vrednosti
#' - Negativne celobrojne vrednosti
#' - Nula
#' - Razmak
#' - Logičke vrednosti
#' - Nazivi
#'
#' #### Pozitivne celobrojne vrednosti
#'
studenti[1, ]

studenti[, 2]

studenti[1, 2]

#' Na ovaj način izvršena je selekcija prvog reda i druge kolone. Pored zadavanja jedne vrednosti, možemo izvršiti selekciju podataka skupom indeksa.
studenti[1, c(2,3)]
studenti[1, c(2:5)]

#' Rezultat upita je samo prikaz - kopija vrednosti. Rezultat možemo dodeliti novoj promenljivoj:

Boris <- studenti[1, c(1:14)]
Boris

#' Isti sistem notacije se koristi i kod drugih tipova podataka, npr. kod vektora:
vec <- c(6, 1, 3, 6, 10, 5)
vec[1:3]

#' Bitno je zapamtiti da indeksiranje u R-u **uvek počinje od 1**, dok za razliku od nekih drugih programskih jezika počinje od 0.
#'
#' #### Negativne celobrojne vrednosti
#' Negativne vrednosti daju suprotni rezultat u odnosu na pozitivne celobrojne vrednosti. Rezultat je sve osim elemenata navedenih indeksom:
studenti[-c(2:35), 2:5]

#' Kombincija pozitivnih i negativnih indeksa je moguća, dok nije moguće postaviti pozitivnu i negativnu vrednost u okviru istog inndeksa:
# studenti[-c(-1,1), 2]
# Error in x[i] : only 0's may be mixed with negative subscripts

studenti[1:5, -1]

#'
#' #### Nula
#' Kao što je rečeno indeksiranje elemenata počinje od 1, dok indeks 0 nije greška, već je rezultat objekat bez elemenata:
#'
studenti[0, 0]

#'
#' #### Razmak
#' Korišćenem razmaka - praznog indeksa, dobija se rezultat koji podrazumeva sve elemente datog reda ili kolone:
#'
studenti[1, ]

#'
#' #### Logičke vrednosti
#' Vrednost indeksa može biti i logička vrednost i tom slučaju rezultat je red i/ili kolona koja odgovara vrednosti TRUE:
#'
studenti[1, c(FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)]

#' Vektor logičkih vrednosti moguće je kreirati primenom logičkih upita. Odnosno kreiranjem logičkog upita dobija se vektor sa vrednostima TRUE i FALSE koji se mogu koristiti za određivanje pozicije vrednosti koju želimo izmeniti:
#'
generacija_2017 <- studenti$god.upisa == 2017
generacija_2017 # vektor logičkih vrednosti

studenti[generacija_2017, ]

#'
#' Logički operatori su veoma efikasan način selekcije i u okviru R-a definisani su na sledeći način:
#'
#'
#' #### Bulovi operatori
#'
#' #' Bulovi operatori nam omogućuju da kombinujemo logičke izraze. Međutim, tu treba imati na umu da `NA` vrednosti mogu uticati na rezultat izraza. Bilo koji izraz sa `NA`vrednošću nam kao rezultat vraća `NA` vrednost.
#'
#+ echo = FALSE, warning = FALSE, message = FALSE, fig.width = 10, fig.height = 8, fig.align='center'
knitr::include_graphics("Figures/logicki operatori.jpg")
#'

#'
#' Na primer, ako želimo pogledati  koji studenti su imali 100 bodova junskom roku i kranju ocenu 9, nećemo dobiti željeni rezultat, upravo zbog prisustva `NA` vrednosti
#'
studenti[studenti$Jun == 100 & studenti$Ocena == 9, ]

studenti[!is.na(studenti$Jun) & !is.na(studenti$Ocena) & studenti$Jun == 100 & studenti$Ocena == 9, ]

#'
#'
#'
#' #### Nazivi
#'
#' Selekcija podataka - elementa je moguća i putem naziva kolona i/ili redova ako su dostupni:

names(studenti)
studenti[, "Prezime"]
studenti[1:5, c("Prezime", "Ime", "br.ind", "god.upisa")]

#' Kao i kombinacija navedenog:
studenti[1:5, c(names(studenti[, c(2:5)]))]

#'
#' ### Selektovanje podataka putem $ sintakse
#' Putem prethodnih primera pokazan je osnovni način selekcije elementa iz skupa podataka. Način selekcije podataka koji se najčešče koristi predstavlja upotrebu $ sintakse.
#' Potrebno je napisati naziv objekta - data frame-a a zatim napisati naziv kolone odvojen znakom "$":
#'
studenti$Prezime

#' *Tips: Nakon napisanog znaka "$" moguće je pritisnuti taster TAB na tastaturi kako bi dobili listu naziva kolona.*
#' Kako bi izvršili upit po redu, potrebno je napisati [] zagrade i navesti indeks reda.
#'
studenti$Prezime[1]
studenti$Prezime[1:5]

#'
#'
#' ### Selektovanje podataka u okviru `list` - e
#'
#' Selektovanje podataka u okviru liste vrši se korišćenjem operatora `[]` i `[[]]` ili prema nazivu elementa liste.
#' Na primer, kreiraćemo listu studenata sa dva elementa, oni koji su položili praksu i onih koji nisu položili praksu.
#'
praksa_list <- list(polozili = studenti[!is.na(studenti$Praksa), ], nisu_polozili = studenti[is.na(studenti$Praksa), ])
#'
#' Ukoliko želimo selektovati prvi član liste primenom operatora `[]`, za rezultat ćemo takođe dobiti listu!
#'
praksa_list[1]

class(praksa_list[1])
#'
#+ echo = FALSE, warning = FALSE, message = FALSE, fig.width = 10, fig.height = 7, fig.align='center'
knitr::include_graphics("Figures/selektovanje_liste.jpg")
#'
#' Međutim, ukoliko želimo selektovati prvi član liste primenom operatora `[[]]`, za rezultat ćemo takođe dobiti `data.frame`!
#'
praksa_list[[1]]
class(praksa_list[[1]])

#'
#' Element liste moguće je selektovati i naznačavanjem imena liste u okviru operatora `[]`:
#'
praksa_list["polozili"]

praksa_list[["polozili"]]
#'
#'
praksa_list[1]
class(praksa_list[1])
#'
#' >
Zadatak

#' > + Kreirati listu tako što da studenti upisani iste godine čine jedan član liste. Za te potrebe koristiti komandu `list(prvi data.frame, drugi data.frame, treci data.frame)`
#'
#'
#'
#'
#'
#' ## Modifikovanje podataka
#'
#'
#' ### Promena vrednosti
#'
#' Modifikacija vrednosti podataka odnosi se na promenu vrednosti nekog podatka. Da bi neku vrednost bilo moguce promeniti, potrebno je prvo specificirati tačnu poziciju vrednosti koju želimo promeniti. Na primer, ako želimo da upišemo kao godinu upisa broj 2017 umesto 17, i 2016 umesto 16, to cemo uraditi na sledeci nacin:

studenti[studenti$god.upisa == 17, "god.upisa"] <- 2017

studenti[studenti$god.upisa == 16, "god.upisa"] <- 2016

studenti$god.upisa

#' Ukoliko žeilimo da svim studentima koji su upisali fakultet 2017 godine dodelimo ocenu 5 iz IG1, to možemo uraditi na sledeći način:

studenti[studenti$god.upisa == 2017, "Ocena"] <- 5
studenti <- read.csv(file = "C:/R_projects/Nauka_R/Slides/data/Students_IG1.txt", header = TRUE, stringsAsFactors = FALSE)
#'
#' >
Zadatak

#' > + Izmeniti rezultate krajnje ocene i prakse za svoje ime tako sto cete dodeliti ocenu 10.

#'
#' #### Modifikovanje tipa podataka
#'
str(studenti)

unique(studenti$god.upisa)

studenti$god.upisa <- factor(studenti$god.upisa, labels = c("2015", "2016", "2017"))

#' #### Modifikovanje redosleda podataka
#'
#' Ukoliko želimo da poređamo vrste u `data.frame`-u prema vrednostima u nekoj koloni, to možemo učiniti na sledeći način:
#'
studenti[order(studenti$Ocena, studenti$Praksa),]
#'
#' #### Kombinovanje podataka
#'
#' Kombinovanjem podataka se odnosi na mogućnost spajanja dve tabele. Za te potrebe učitaćemo rezultate (konačne ocene) studenata postignute na predmetima IG1, Praksa i IG2.
#'
ig1 <- readxl::read_xlsx(path = "C:/R_projects/Nauka_R/Slides/data/Students_IG1.xlsx", sheet = "Students")
head(ig1)
ig1 <- ig1[, c("Prezime", "Ime", "Ocena", "Praksa")] # Selektovali smo samo kolone koje nas zanimaju.
names(ig1) <- c("prezime", "ime", "ocena_ig1", "ocena_praksa")

ig2 <- readxl::read_xlsx(path = "C:/R_projects/Nauka_R/Slides/data/Students_IG2.xlsx", sheet = "Students")
head(ig1)
ig2 <- ig2[, c("Prezime", "Ime", "Ocena")] # Selektovali smo samo kolone koje nas zanimaju.
names(ig2) <- c("prezime", "ime", "ocena_ig2")

#' Komanda `cbind` spaja dve tabele tako što drugu "nalepi" na prvu. Kao rezultat se dobija tabela sa ponovljenih kolonama koje su zajedničke. Uslov za korišćenje komande `cbind` je da dve tabele imaju isti broj vrsta.

ig <- cbind(ig1, ig2)
ig

#' Analogno komandi `cbind`, postoji komanda `rbind` koja spaja dve tabele tako što ih nadovezuje jednu ispod druge. Uslov za korišćenje komande `rbind` je da dve tabele imaju isti broj kolona.

#' Ukoliko postoje zajedničke kolone poželjno je da se one ne ponavljaju. U tu svrhu koristićemo komandu `merge`:
#'
ig <- merge(ig1, ig2, by = c("prezime", "ime"))

ig
#'
#'
#' ## Sumiranje
#'
#' Sumiranje podataka je moguće uraditi po vrednostima reodova i/ili kolona. Postoji veliki broj funkcija, kao i paketa koji koriste svoje funkcije za sumiranje po određenim pravilima. Neke od osnovnih funkcija base paketa su:
#'
#' ### Base funkcije
summary(studenti)

mean(studenti$Ocena, na.rm = TRUE) # "na.rm" parametar se koristi kako bi se zanemarile NA vrednosti u podacima.

min(studenti$kol.1, na.rm = TRUE)
max(studenti$kol.1, na.rm = TRUE)

median(studenti$Praksa, na.rm = T)

#'
#' ### apply i lapply funkcije
#' apply i lapply funkcije kao ulaz koriste data.frame ili matricu i kao rezultat daju vektor, listu ili array.
## ?apply()
## ?lapply()
#' apply možemo koristiti kako bi izvršili sumiranje po svim redovima (drugi argument funkcije je 1) ili kolonama (drugi argument funkcije je 2).
#'
studenti_bez_na <- studenti
studenti_bez_na[is.na(studenti_bez_na)] <- 0
apply(studenti_bez_na[, 6:14], 2, mean)

#' lapply koristimo kada želimo da izvršimo sumiranje po svakom članu liste ili npr. svakoj koloni data.frame-a. Razlika u odnosu na apply je što je ovde rezltat lista,
#'
lapply(studenti_bez_na[, 6:14], mean)

#' ### Funkcije colSums() i rowSums()
#'
colSums(studenti[, 6:14], na.rm = T)
rowSums(studenti[, 6:7], na.rm = T) # Rezultat je zbir bodova na prvom i drugom kolokvijumu

colMeans(studenti[, 6:14], na.rm = T) # Uočavamo razilku između srednje vrednosti kolona dobijene funkcijom apply i colSums. Razlika je u tome da smo u prvom slučaju NA vrednosti zamenili sa 0 (pa je delilac veći) u odnosu na funkciju colSums gde smo naznačili da zanemarujemo NA vrednosti.
rowMeans(studenti[, 6:7], na.rm = T)

#'
#' ### Funkcija by()
#' Koriscenjem funkcije by(), možemo na jednostavan način uraditi sumiranje po određenim faktorskim kolona.
by(studenti, studenti[, 5], summary) # Sumarni rezultati po godini upisa

#' ### Kreiranje jednostavne funkcije
#' U cilju sumiranja podataka po određenom pravilu, možemo napisati jednostavnu funkciju:
#'
racunajSrednjuVrednost <- function(data_frame = data_frame, izbaciNA = TRUE){ # argumenti funkcije
  sr_vrednost  <- mean(data_frame$Ocena, na.rm = izbaciNA)
  return(sr_vrednost)
}

racunajSrednjuVrednost(data_frame = studenti, izbaciNA = TRUE)

#'
#' >
Zadatak

#' > + Sumirati podatke i sračunati ukupan broj studenata koji su položili prvi kolokvijum.
#' > + Sumirati podatke i sračunati ukupan broj studenata koji su položili oba kolokvijuma.
#' > + Sumirati podatke i sračunati koliko su bodovi na prvom i drugom kolokvijumu u korelaciji sa krajnjom ocenom.
#'
#' Rešenje:
#'

#' Zadatak 1:
length(studenti_bez_na$kol.1[studenti_bez_na$kol.1 > 0])

#' Zadatak 2:
length(studenti_bez_na$kol.1[studenti_bez_na$kol.1 > 0 & studenti_bez_na$kol.2 > 0])

#' Zadatak 3:
cor(studenti_bez_na$kol.1, studenti_bez_na$Ocena)
plot(studenti_bez_na$kol.1, studenti_bez_na$Ocena)

cor(studenti_bez_na$kol.2, studenti_bez_na$Ocena)
plot(studenti_bez_na$kol.2, studenti_bez_na$Ocena)
#'
#'
#'
#' # Eksportovanje podataka u R-u
#'
#' Osnovna funkcija za eksportovanje podataka u R-u je `write.table`. Međutim, češće se koriste tzv. `wrapper` funkcije koje pozivaju funkciju `write.table` ali sa predefinisanim `default` parametrima, kao na primer `write.csv`.
#'
#'
write.csv(studenti, file = "studenti_export.csv", row.names = FALSE)
#'
#' ## `writexl` paket
#'
#' Paket `writexl` je veoma jednostavan paket za kreiranje `excel` fajlova. Ima svega nekoliko veoma korisnih funkcija.
#+ eval = FALSE
install.packages("writexl")
library(writexl)
#+ eval = FALSE
writexl::write_xlsx(studenti, path = "studenti_excel.xlsx")
#'
#'
#' ## Čuvanje i učitavanje R podataka
#'
#' Podaci (objekti svih vrsta) kreirani u okviru R-a, mogu biti sačuvani kao `Rdata` (ukoliko je više objekata) ili `rda` (`rds`) (ukoliko je jedan objekat)
#+ eval = FALSE
save(studenti, file = "C:/R_projects/Nauka_R/Slides/studenti_export.rda")

#'
#'


count <- 0

while (count < 10){
  print(count)
  count = count + 1
}

v <- 9  # same thing but using a variable instead of retyping a digit
count <- 0

while (count < v){
  print(count)
  count = count + 1
}

x <- 10
count <- 0
values <- rep(NA, x)

while (count < x){
  print(values)
  count = count + 1
  values[count] <- count
}

x <- 10
i <- 0
values <- rep(NA, x)

while (i < x){
  print(values)
  i = i + 1
  values[i] <- i
}


# Exercise 3
#
# Time: 5 minutes

# 1) Convert the following character vector to a factor:

colors <- c("Red", "Blue", "Green", "Yellow", "Black", "Red", "Blue", "Green", "Black", "Red", "Blue", "Green", "Yellow", "Black", "Red", "Blue", "Green", "Black", "Green", "Green")

# 2) What command will print only the non-missing values in the following vector?

v <- c(1, 2, 3, NA, 5, 6, NA, NA)

# 3) How would you permanently remove all NA's from 'v'?


"
Исследовать различие в работе логических операторов «Поэлементное И» и «Сокращенное И»,
для чего подготовить примеры, аналогичные примерам из п.9.
"

first = TRUE
second = FALSE

print(!first)

print(first & second)
print(first && second)
print(first | second)
print(first || second)


## Exercício 5
## Prof. James Hunter
## from: https://rstudio.cloud/project/1181159
## 12 de maio de 2020

# Passo 1: Carregar Pacotes Necessários
library(tidyverse)
library(summarytools)

# Passo 2: Colocar starwars na memoria como "sw" utilizando so
#          variáveis name até species; 2 alternativas
sw <- starwars[, 1:10] # base R--todas as fileiras, colunas 1:10
sw <- starwars %>%             # tidyverse
  select(name:species)

# Passo 3: Olhar na estrutura dos dados
str(sw)

# Passo 4: Olhar em todas as variáveis

summarytools::dfSummary(sw, graph.col = FALSE)


a <- as.double(readline(prompt = "Enter a:"))
b <- as.double(readline(prompt = "Enter b:"))

if ( a < b) {
  print(' b is bigger number ')
} else {
  print('a is bigger number')
}

# Or you case use ifelse(a < b, 'b is bigger', 'a is bigger')


# --------------------------
#  App Title: Longest Run
#     Author: Jimmy Doi
# --------------------------

library(shiny)

# Define the overall UI
shinyUI(

  # Use a fluid Bootstrap layout
  fluidPage(

  tags$head(tags$link(rel = "icon", type = "image/x-icon", href =
  "https://webresource.its.calpoly.edu/cpwebtemplate/5.0.1/common/images_html/favicon.ico")),

    # Give the page a title
    tags$title("Longest Run of Heads or Tails"),
    titlePanel("Longest Run of Heads or Tails"),

    div("Note: Please adjust width of browser if only one column is visible.",
        style = "font-size: 9pt;color:teal"),br(),

    # Generate a row with a sidebar
    sidebarLayout(

      # Define the sidebar with one input
      sidebarPanel(

        sliderInput("trials",
                    label = h5(HTML((paste0("Number of trials (", em("n"),"):")))),
                    min = 10, max = 400, value = 200, step=10),br(),

        sliderInput("minrun",
                    label = h5("Mark run lengths of at least ..."),
                    min = 2, max = 15, value = 5, step=1),
        div("Change of specified run length will impact marked runs in current plot", style = "font-size: 9.5pt;color:teal",align="right"),br(),

        sliderInput("my.cex",
                    label = h5("Font size:"),
                    min = 1, max = 10, value = 4, step=1
                    ),br(),

        checkboxInput("checkbox", label = "Include predicted longest run and
                      prediction interval", value = TRUE),

        checkboxInput("showProp", label = "Modify probability of heads", FALSE),
        conditionalPanel(condition="input.showProp",
               sliderInput("H.prob", label=NULL,
                           #label = h5("Probability of Heads"),
                           min = .01, max = .99, value = .5, step=.01)
            )#end conditionalPanel
        ,

        div(actionButton("save", label="Generate"),align="right"),
        div("Click", tags$b("Generate")," to re-randomize outcomes based on current number of trials", style = "font-size: 9.5pt;color:teal",align="right"),br(),

        br(),

        div("Shiny app by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Base R code by",
            a(href="http://statweb.calpoly.edu/jdoi/",target="_blank",
              "Jimmy Doi"),align="right", style = "font-size: 8pt"),

        div("Shiny source files:",
            a(href="https://gist.github.com/calpolystat/eee9a9e00dd4ddd68614",
              target="_blank","GitHub Gist"),align="right", style = "font-size: 8pt"),

        div(a(href="http://www.statistics.calpoly.edu/shiny",target="_blank",
              "Cal Poly Statistics Dept Shiny Series"),align="right", style = "font-size: 8pt")
      ),

      # Create a spot for the barplot
      mainPanel(

        plotOutput("coinPlot", width="100%"), HTML("<hr style='height: 2px; color: #de7008;
                                                   background-color: #df7109; border: none;'>"),

        p("If a fair coin is flipped 100 times and a streak of 7 heads (or tails) in a row is
          observed, is that an unusual result? To answer this we can simulate tosses of a fair
          coin and keep track of runs of heads or tails.",style="margin-top:-10px"),
        p("This Shiny app allows you to simulate the outcomes of a coin flipped",
          HTML(paste(em("n"),sep="")), "times. You can specify the probability of heads
          (default is 50%). Any runs of at least the length you specify will
          be marked in color, and the length of the longest run will be given. You may also choose
          to display the predicted approximate length of the longest run and an approximate 95%
          prediction interval for the length of the longest run. Details on these two estimators
          can be found in the first reference below.") ,

        p("More information on the length of the longest run can be found in the following journal
       articles:"),

        div("Schilling, M. 'The Longest Run of Heads'",
            em("The College Mathematics Journal"),", 21(3), 196--207", style="padding-left: 20px;
            display:block; border-left: 5px solid #faebbc;margin-left:0px"),
        div("Schilling, M. 'The Surprising Predictability of Long Runs'",
            em("Mathematics Magazine"),", 85(2), 141--149", style="padding-left: 20px; display:block;
            border-left: 5px solid #faebbc;margin-left:0px")
      )

    )
  )
)


## R for SQL Professionals Lab (Student).R
## Buck Woody, Microsoft
## Last Updated: 25 July 2017
## Based on the CRAN Course located here:https://cran.r-project.org/doc/manuals/r-release/R-intro.html
## You will read through the material below along with the course "R for SQL Professionals"
## Anything using one # or two ## signs is for you to read and follow along, anything with ### is your assignment when you get to that portion of the class.
## Note - R Allows you to work with Statistics, which this course does not cover. You should be familiar with the following terms:
## Finite and infinite probability, Joint/addition/multiplication/conditional probability operations, Combination and permutation, the seven fundamental rules of probability theory, Random sampling, Over - fitting, Sampling with and without replacement, Histograms and ogives, Cumulative percentages, Population distribution, Stem and leaf graphs, S - shaped curve, Data distribution(middle value measurements and range), Central tendency and dispersion(variance), Tchebysheff Inequality Theorem, Central Limit Theorem, Binomial distributions, Normal distribution,  Chi - squared, t and F distributions, Hypothesis testing, Confidence intervals, Standard error, Type I and II errors, Correlation, Regression, Significance testing, Cross validation, jackknife and bootstrap replication of study

#1.0 Planning, setup and environment
	##1.1 R Ecostructure, Installation
	##1.2 Microsoft R
	##1.3 R Client and Environment
		### Start the HTML interface to on-line help (using a web browser available at your machine). OPen help this way and briefly explore the features of this facility with the mouse:

		### Show one example of the help function. Is there more than one way to do that?

		### Show the R version:

		### Show all system environment settings:

		## These are stored in the "Workspace", which is persisted at .RData
		## The commands you type are persisted in .Rhistory
		## ( More on workspaces here - http://www.statmethods.net/interface/workspace.html)
		### Show the Working Directory:

		### Set it with setwd() to a temporary location:

		### Show the files in your R home directory:

		### Save your Workspace:

		## Show the files in your Workspace:
		list.files(all.files = "TRUE")
		### Remove individual objects no longer needed, show all currently loaded objects:
		x <- 10
		X <- 5

		## Danger: rm(list = ls()) removes everything, so use with care! (There is no "Recycle Bin")

		## .Rprofile - http://www.statmethods.net/interface/customizing.html
		## Edit the .Last element of the .Rprofile file to print "Goodnight, Dave" when you exit
		## .Last <- function(){cat("\n Goodnight, Dave. \n")}

		### Show the sample data sets in R, obtain help for one of them:

		### Using the anscombe sample dataset, view the data and then edit it in a graphical window:

		## Programming and Flow
		x <- 1
		if (x > 1) "Higher than 1" else "Not higher than 1"

		0xFFFF

		### loop types
		i <- 5
		repeat { if (i > 25) break else { print(i); i <- i + 5; }}

		i <- 5
		while (i <= 25) { print(i); i <- i + 5; }

		for (i in seq(from = 5, to = 25, by = 5))
			print(i)

		install.packages("iterators")
		library(iterators)
		help.search("iterators")

		i <- iter(1:5)
		nextElem(i)

		### Clean up - use with care!

	#1.4 Package Management
		### Show the libraries that are currently loaded:

		### Show the libraries that are available:

		### Show how to get help with one of them:

		### Show where R stores packages:

		### Install the dplyr package:

		### Update all packages:

		## More info on packages for MRS: https: / / msdn.microsoft.com / en - us / library / mt591989.aspx
		## More great packages - http://www.computerworld.com/article/2921176/business-intelligence/great-r-packages-for-data-import-wrangling-visualization.html

		## Remove a Package
		? remove.packages

#2.0 Data Structures - http://adv-r.had.co.nz/Data-structures.html
	##2.1 R Data Types
	##2.2 R Data Structures

	### Create an object holding a range of values from 1 to 20. Create another object showing whether all values are higher than 15. Show the type of the two objects:

	### Create an object and cast an object to another class:

	## Lengths of objects

	### Make an object of a given length:

	### Truncate the length:

	### Clean up - use with care!

		#2.2.1 Vectors
		### Vectors have implied distribution during operations. Set up two objects - x and y. Make x a vector from 1 to 10, and y a vector of 2 * x. Show both x and y. Then show the 4th element of y:

		## Logical vectors are generated by conditions
		temp1 <- x > 7
		temp1
		## And repetition is very useful
		s5 <- rep(x, times = 5)
		s5
		### Make a new object that replicates the numbers 1-7, seven times:

		#2.2.2 Lists
		## Lists can mix item types:
		Lst <- list(name = "Fred", wife = "Mary", no.children = 3, child.ages = c(4, 7, 9))
		Lst
		Lst[2]
		Lst$name
		Lst[["name"]]

		### Create an object called pts that uses the cars sample data to create an x-value of the speed and a y-value of the distance. then type plot(pts) to show the result:

		#2.2.3 Matrix
		### Create an object from 1-20, then create a 2-dimension matrix from that object, then show the 3rd value from the second dimension:

		#2.2.4 Array
		## You can create an array with the dim function
		z <- c(1:24)
		dim(z) <- c(3, 4, 2)
		z

		### Create a A 4x5 array using an array function:

		### Show 3rd row, 2nd column:

		### Replace that value with 0:

		## You can make this look more like tables and rows, with headers and names
		x1 <- c(1, 2, 3)
		x2 <- c(4, 5, 6, 7, 8, 9)
		matrix.name <- c("Mat1", "Mat2")
		column.name <- c("Col1", "Col2", "Col3")
		row.name <- c("Row1", "Row2", "Row3")
		y <- array(c(x1, x2), dim = c(3, 3, 2), dimnames = list(row.name, column.name, matrix.name))
		y
		y[,, 2]

		## You can perform math across arrays with apply: array, data set, function
		x
		sums <- apply(x, 1, sum) # sum the rows across
		sums
		sums <- apply(x, 2, sum) # sum the columns down
		sums
		### Clean up - use with care!

		## Dataframes
		## Data frames are similar to a Matrix, but different "columns" can have different datatypes.
		x <- c(10, 20, 30)
		y <- c("Red", "Green", "Blue")
		z <- c(TRUE, FALSE, TRUE)
		df <- data.frame(x, y, z)
		df

		## Dates - and the lubridate package
		startDate <- as.Date("2017-12-25")
		endDate <- as.Date("2018-12-25")
		elapsedDays <- endDate - startDate
		elapsedDays

		### Get the difference in dates in weeks

		install.packages("lubridate")
		vignette("lubridate")

#3.0 Data Ingress and Connection Options
	#3.1 Scripts
		## Load an R Script:
		source("c:\\temp\\SampleScript.R")

	#3.2 Reading in data from a file
		## Reads a file in from c:\temp and uses the first lines as headers
		HousePrice <- read.table("c:\\temp\\houses.csv", header = TRUE)
		### Use a graphical menu to select a file and it read in, and explore that data (you may have to create one first):

		### Read the file "		data <- read.csv("https://aql.datapress.com/leeds/dataset/polling-station-locations/2016-03-17T10:33:18/Polling%20stations.csv")" and load it into an object called webdata
		data <- read.csv("https://aql.datapress.com/leeds/dataset/polling-station-locations/2016-03-17T10:33:18/Polling%20stations.csv")

	#3.3 Exporting Data
		## Send all output to file
		sink("c:\\temp\\output.txt")
		## Return to sending to StdOut
		sink()
		### Open a sample dataset, assign it to an object of x, and write the x object as data out:

	## 3.3 Working with ODBC
	## Note: Refer to https://packages.revolutionanalytics.com/doc/8.0.0/win/RevoScaleR_ODBC.pdf for a comprehensive discussion on working with ODBC data sources in Microsoft R.
	## Create the SQL Statement you want
	bikesSQL = "SELECT * FROM Production.Product"
	## Point to the ODBC DSN Name
	bikesDS2 <- RxOdbcData(sqlQuery = bikesSQL, connectionString = "DSN=MSSQLDSN;Uid=<username>;Pwd=<password>;")
	## A place to store the returned data - using the Extended Data Frame function
	bikesFile <- RxXdfData("DataFromODBC.xdf")
	## Move the data to the file
	rxImport(bikesDS2, bikesFile, overwrite = TRUE)
	## Display information about the file
	rxGetInfo(bikesFile, getVarInfo = TRUE, numRows = 10)

	### Clean up - use with care!

#4.0 R Functions
	## 4.1 Basic Functions:
	x <- cars
	str(x)
	mean(x$speed)
	median(x$speed)
	quantile(x$speed)
	sum(x$speed)
	sd(x$speed)
	rbind(x$speed)
	y = merge(x$speed, x$dist)
	y
	order(x$speed)

	#4.2 Quantitative Analysis (Continuous, Numeric Values)
	? faithful
	attach(faithful)
	View(faithful)
	summary(eruptions)
	fivenum(eruptions)
	plot(eruptions)
	hist(eruptions)
	stem(eruptions)
	range(eruptions)
	seq(1.5, 5.5, by = .5)
	table(cut(faithful$eruptions, seq(1.5, 5.5, by = 0.5)))

	#4.3 Qualitative Analysis
	## Aggregate is a useful parsing tool for qualitative measurements
	? chickwts
	attach(chickwts)
	aggregate(weight ~ feed, data = chickwts, mean)
	### Create a simple plot of the data above:

	## Tables are a more powerful way to work with arrays of data
	price <- matrix(c(53, 47, 21, 90, 45, 15, 65, 27, 11), ncol = 3, byrow = TRUE)
	colnames(price) <- c("High", "Middle", "Low")
	rownames(price) <- c("Stock1", "Stock2", "Stock3")
	price <- as.table(price)
	prop.table(price) # proportions of all rows and columns
	prop.table(price, 1) # proportions of rows
	prop.table(price, 2) # proportion of columns

	### A far more common tool for qualitative selection and "wrangling" of data is dplyr. Install it:
	install.packages("dplyr")
	library(dplyr)
	# Documentation: https://www.r-project.org/nosvn/pandoc/dplyr.html

	### Get the data for most examples:
	install.packages(c("hflights", "Lahman"))

	### Work through this tutorial:
	vignette("introduction", package = "dplyr")

	## More information on how dplyr works - you can look up examples for using each of these:
	select() # Like the SQL SELECT Statement
		# starts_with()
		# ends_with()
		# contains()
		# matches()
		# num_range()
		# one_of()
		# everything()

	filter() # Like the SQL WHERE Statement - remember, R uses == for equality test. Can also be use with %in%
	group_by() # Like the SQL GROUP BY Statement
	summarise() # Like the SQL aggregate statements
	arrange() # Like the SQL ORDER BY Statement
	join() # Like the SQL JOIN Statement
			# inner_join()
			# left_join()
			# semi_join()
			# anti_join()
			# intersect()
			# union()

	mutate() # Like the SQL ALIAS Statement
	distinct() # Like the SQL DISTINCT Statement
	do() # Like SQL Cursors

	#4.4 Probability Analysis
	### Look up the help for at least three of the functions below, locate an example, type and run it here:
	help(qnorm)
	beta()
	log()
	gamma()
	logis()
	norm()
	pois()
	t()
	unif()
	chisq()

	## Predictions
	x <- rnorm(15)
	y <- x + rnorm(15)
	predict(lm(y ~ x))

	new <- data.frame(x = seq(-3, 3, 0.5))
	predict(lm(y ~ x), new, se.fit = TRUE)
	pred.w.plim <- predict(lm(y ~ x), new, interval = "prediction")
	pred.w.clim <- predict(lm(y ~ x), new, interval = "confidence")
	matplot(new$x, cbind(pred.w.clim, pred.w.plim[, -1]),
		lty = c(1, 2, 2, 3, 3), type = "l", ylab = "predicted y")

	#4.5 Creating your own functions
	myFunction <- function(arg1, arg2, ...)
	{
			#statements...
		return(object)
	}

		### Create a function that calculates the amount of money spent on a meeting by the number of people in that meeting. If the cost is higher than 1,000, tell the person they are wasting money:

#5.0 Visualization - check out http://www.joyce-robbins.com/wp-content/uploads/2016/04/effectivegraphsmro1.pdf
	## packages: base, ggplot2, lattice, HH, MASS and micromapST

	#5.1 Plot
	## Example for cars dataset
	require(stats) # for lowess, rpois, rnorm
	plot(cars)
	lines(lowess(cars))
		## Sine Wave Plot
	plot(sin, - pi, 2 * pi)

	## Discrete Distribution Plot:
	plot(table(rpois(100, 5)), type = "h", col = "red", lwd = 10, main = "rpois(100, lambda = 5)")

	## Simple quantiles/ECDF, see ecdf() {library(stats)} for a better one
	plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
	points(x, cex = .5, col = "dark red")

	#5.2 Boxplot
	## Two samples of data, showing the latent heat of the fusion of ice
	A <- c(79.98, 80.04, 80.02, 80.04, 80.03, 80.03, 80.04, 79.97, 80.05, 80.03, 80.02, 80.00, 80.02)
	B <- c(80.02, 79.94, 79.98, 79.97, 79.97, 80.03, 79.95, 79.97)
	### Create a box plot using A and B data from above:

	#5.3 Histograms
	attach(faithful)
		### Examine the faithful dataset. What is it? What does it show? How can we graph the eruptions?

	#5.4 Barplot
	barplot(x, y)

	#5.5 Piechart
	x <- c(1, 6, 7, 4, 1)
	pie(x)

	### Using the anscombe dataset, create a visual for the data:

#### 6: Optional full examples

# An interesting experience, which puts your knowledge together -
# Wordcloud in R
# https://cran.r-project.org/web/packages/wordcloud/wordcloud.pdf
install.packages("tm")
install.packages("wordcloud")
install.packages("SnowballC")
require(tm)
require(wordcloud)
require(SnowballC)
## - Note: Create a directory, and any files you put there will be read in by this command!
x <- Corpus(DirSource("d:/test/"))
inspect(x)
x <- tm_map(x, stripWhitespace)
x <- tm_map(x, tolower)
x <- tm_map(x, removeWords, stopwords("english"))
x <- tm_map(x, stemDocument)
wordcloud(x, scale=c(5,0.5), max.words=100, random.order=FALSE, rot.per=0.35, use.r.layout=FALSE, colors=brewer.pal(8, "Dark2"))

## make the bins smaller, make a plot of density
hist(faithful$eruptions, seq(1.6, 5.2, 0.2), prob = TRUE)
lines(density(faithful$eruptions, bw = 0.1))
rug(faithful$eruptions) # show the actual data points

## Two samples of data, showing the latent heat of the fusion of ice
A <- c(79.98, 80.04, 80.02, 80.04, 80.03, 80.03, 80.04, 79.97, 80.05, 80.03, 80.02, 80.00, 80.02)
B <- c(80.02, 79.94, 79.98, 79.97, 79.97, 80.03, 79.95, 79.97)
boxplot(A, B)
### Are they significantly different? (yes)
t.test(A, B)

# A complete example using sample data
## Get the path to the data file.
filepath <- system.file("data", "morley.tab", package = "datasets")
filepath
## Look at the file
file.show(filepath)
## Read in the Michelson data as a data frame, and look at it. There are five experiments (column Expt) and each has 20 runs (column Run) and sl is the recorded speed of light, suitably coded
mm <- read.table(filepath)
mm
## Change Expt and Run into factors
mm$Expt <- factor(mm$Expt)
mm$Run <- factor(mm$Run)
## Make the data frame visible at position 3 (the default)
attach(mm)
## Compare the five experiments with simple boxplots
plot(Expt, Speed, main = "Speed of Light Data", xlab = "Experiment No.")
## Analyze as a randomized block, with �runs� and �experiments� as factors.
fm <- aov(Speed ~ Run + Expt, data = mm)
summary(fm)
## Fit the sub-model omitting runs, and compare using a formal analysis of variance
fm0 <- update(fm, . ~ . - Run)
anova(fm0, fm)
## Clean up before moving on
detach()
rm(fm, fm0)

# Ordered and unordered factors
# A sample of 30 tax accountants from Australia
state <- c("tas", "sa", "qld", "nsw", "nsw", "nt", "wa", "wa",
			 "qld", "vic", "nsw", "vic", "qld", "qld", "sa", "tas",
			 "sa", "nt", "wa", "vic", "qld", "nsw", "nsw", "wa",
			 "sa", "act", "nsw", "vic", "vic", "act")

## Group those into a factor set, show the groupings
statef <- factor(state)
levels(statef)
table(statef)
## The salaries, in thousands, for the accountants
incomes <- c(60, 49, 40, 61, 64, 60, 59, 54, 62, 69, 70, 42, 56,
			   61, 61, 61, 58, 51, 48, 65, 49, 49, 41, 48, 52, 46,
			   59, 46, 58, 43)
## Now we can use tapply to put them together
incmeans <- tapply(incomes, statef, mean)
incmeans

## the cut function can break things further into ranges:
wfact <- cut(incomes, breaks = 3, labels = c("Low", "Med", "High"))
wfact
table(wfact)

## Ordered example:
m <- c("March", "April", "January", "November", "January", "September", "October", "September", "November", "August", "January", "November", "November", "February", "May", "August", "July", "December", "August", "August", "September", "November", "February", "April")
m = factor(m)
table(m)

om <- factor(m, levels = c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"), ordered = TRUE)
table(om)

########################### EOF: R for SQL Professionals Lab (Student).R

ML for SQL/ML Services for SQL Server/oldcode/Code/ml_for_sql_server_lab_r.r


"
Ввести с клавиатуры число N. Проверить, является ли N целым числом.
"
{
  N <- readline("Введите число N  -> ")

  if (length(N)>0 & is.numeric(N)){
    print("Число N является целым")
  }
  else{
    print("Число N НЕ является целым")
  }
}


a = as.integer(readline(prompt = "Enter a"))

b = as.integer(readline(prompt = "Enter b"))

c = as.integer(readline(prompt = "Enter c"))

if((a>b)&&(a>c)){
  cat("a is largest")
}else if(b>c){
  cat("b is largets")
}else {
  cat("c is largest")
}


# Basics Of Data Frame
S.No = 1:5
df <- data.frame("S.No"=S.No,
                 "Name"=c("john","Merry","Joseph","Mohan","Rihanna"),
                 "Age"=c(32,26,20,45,26),
                 "Start-Date"=as.Date(c("2012-01-01","2013-09,32","2014-11-15","2014-05,11","2015-03-27")))
str(df)

# total row
nrow(df)
#total column
length(df)
dim(df)
summary(df)
names(df)
str(df1)
df <- data.frame("S.No"=S.No,
                 "Name"=c("john","Merry","Joseph","Mohan","Rihanna"),
                 "Age"=c(32,26,20,45,26),
                 "Start_Date"=as.Date(c("2012-01-01","2013-09,32","2014-11-15","2014-05,11","2015-03-27")),
                 stringsAsFactors = T)
df
#how to acces data
#use either [.[[ or$ operator to access cols of df
df["Name"]
df[["Name"]]
df$Name
df[2]
df[[2]]
#df$2 #error
df["Name"][2] #error
df[["Name"]][2]
df$Start_Date[5]
#error
df[2][2]  #should be[[
df["Name"][2] #should be [[

df$Start_Date[5]
df[2,2]
df[,2]
df[c(1,3),]
df[3:5,c(1,4)]
df[,-3]

install.packages("tibble")

dept <- c("IT","HR","IT","Finance","Management")
df$Dept <- dept
df
df$Department <- dept
df
#remove column
df<-df[,-5]
df
df$Department <- NULL
df

# add col is using cbind function
emp_id=101:105
emp_id
df <- cbind(df,emp_id)
df$emp_id <-NULL
df
df <- cbind(emp_id,df)
df
df$emp_id <-NULL
# adding col in between using cbind
df <- cbind(df[,1:3],emp_id,df[,4:5])
df

# add col using tibble library
library(tibble)
df3 <- data.frame(x=1:3,y=5:7,z=10:12)
df3
df3 <- add_column(df3,s=11:13,.before="y")
df3
df3 <- add_column(df3,s=11:13,.before=2)
df3$s.1 <- NULL
df3

#bind two df
df <- data.frame("S.No"=6:8,
                  "Name"=c("john","Merry","Joseph"),
                  "Age"=c(32,26,20),
                  "Start_Date"=as.Date(c("2012-01-01","2013-09-30","2014-11-15")),
                  stringsAsFactors = T)

df4 <- data.frame("S.No"=6:8,
                 "Name"=c("john","Merry","Joseph"),
                 "Age"=c(32,26,20),
                 "Start_Date"=as.Date(c("2012-01-01","2013-09-30","2014-11-15")),
                 stringsAsFactors = T)
df4

df5<-rbind(df,df4)
df5
# add row only
df6 <- data.frame("S.No"=9,"Name"="Abhi","Age"=56,"Start_Date"=as.Date("2014-02-01"))
df6
#df5 <- rbind(df5,c(9,"Abhi",56,as.Date("2014-02-01")))
rbind(df5,df6)

#error df5[9:10,1:6] <-NULL
df5<-df5[-9:-10,]
df5


library(tidyverse)
library(viridis)

serengeti = read_csv("http://datadryad.org/bitstream/handle/10255/dryad.86348/consensus_data.csv")
serengeti.behaviours = serengeti[10:11] # a data frame/tibble is a list of columns/variables!
plot_by_species = split(serengeti[10:11], serengeti$Species) #split by species
to_plot = plot_by_species[1:10] #so I don't forget to subset

# after thinking about my comments below I was able to pick up the pattern that
# was causing me trouble. I wrote a blog post on it and posted it here:
# https://camnugent.wordpress.com/2018/01/24/tales-from-the-r-users-group-labeled-lists-lapply-and-the-single-and-double-slice/

# Cam yelling from atop a soapbox:

# 1. The apply family is fun R specific syntactic sugar (which is a tradeoff)
# using the syntactic sugar of R provides the ability to project code along a series
# or dataframe all in one line. This is concise and appears to carry a speed advantage,
# but comes at the cost of being more cryptic and not as intuitive for the
# readers of the code (opposed to the writers of the code).

# 2. x[i] vs x[[i]]
# here is the official documentation on it:
# https://cran.r-project.org/doc/manuals/R-lang.html#Indexing
# Having x[i] return an object with a label on it causes more problems then it solves
# and makes the data structure clunky. My gripe with this (and other things like tibbles)
# is that I have to do extra work to get plain data... the labels are more
# 'sticky' than common sense would suggest they should be

# For example, working with the simplest labelled list possible:

# a list of 3 numbers and their corresponding labels
my_list = list(1,2,3)
names(my_list)= c('a', 'b', 'c')

my_list

# what is at position a?

my_list['a'] # in Cam's utopian R this would just return a plain 1
# but a alas the 'a' label is stuck on top
# paradoxically the type tells me it is a number :/
typeof(my_list['a'])
# but that seems not true because for practical purposes it behaves like a one member list!
# see below when I do math with the data in the  first position of my list,
# I get a LABELLED NUMBER! ugh.
my_list['a'] + 3

names(my_list['a'] + 3)
# long story long the [[i]] should be the default, and the labelled the special case.
# in most instance a naked number makes more sense
my_list[['a']] # this should be what my_list['a'] returns

# 3. What I learned from today's homework is that the lapply sees data from my Utopian R,
# and not the behaviour we see when we call things one at a time from the list.

# Consider the data from the homework, here isolated as to_plot
# it is a labelled list of 5 dataframes

typeof(to_plot) #its a list
to_plot[1] #this gives me a labelled dataframe 'aardvark'
to_plot[[1]] #this gives me just a list without the 'aardvark' label

# based off that, calling the single slice, I can get the label
names(to_plot[1]) #this gives me aardvark
names(to_plot[[1]]) # this gives me "Standing" and "Resting"

# but when I use it in an lapply with an anonymous function, the
# individuals rows (x in the function) don't have the labels
# so names(x[1]) gives me 'standing' and names(x) also gives me 'standing'!
# why can't I access the label in the same way I did with the individual slices
# this disconnect between behaviour in the apply and outside is not intuitive.
# lapply works at the level below the labels, so we can't directly use the labels
# this bothers me because it goes against the convention I was just forced by R
# to adopt in order to work with the labelled list's data in the first place
# within the lapply, we need to give the function another source to access them from

par(mfrow=c(2,5))
lapply(to_plot,
  function(x) { plot(x[[1]], main=names(x[1]) )})

# here is the trick pass the higher up list to the lapply names(the_list) ,
# and call the lower list through an external call to its variable.
# in my opinion there shouldn't need to be a trick though! Trick are inherently complex

lapply(names(to_plot),
  function(x) { plot(to_plot[[x]], main=names(to_plot[x]))})

# 4. I guess the take home message here is that although working with the labelled lists
# in lapply is possible, it was likely not the intended use of the function and therefore
# the syntax required to make it works is a bit unintuitive. I think the best use of lapply
# is to use R's built in functions across a list of dataframes or other things
# i.e. to get a list of means column z in each of the datframes in the list

# Through Jonathan and Nia's discussion answers, I was able to better understand how one can use lapply with
# home made functions, by leveraging the internal anonymous function to apply it to a list
# containg complex data structures (not just numbers) at each position

# 5. I have stumbled upon the real strength of the mapply while doing my homework!
# here I demonstrate this powerful trope with the iris dataset:

# For the point of demonstration, lets say that the petals in the dataset are all triangles
# and I want to find the area of the petals. With the length of the petal being the base, and
# the width of the petals being the height.

# I write a function that calculates that, and mapply it to the whole dataframe at once
head(iris) #recall the columns

# my triangle area function
tri_area = function(base, height){
  (base * height) / 2
}

# here we make a new column Petal.Area using the mapply to run the tri_area function for all
# the rows in the dataframe at once. mapply lets you make a column or columns the input,
# and create a column that is the output! Thats neat!

iris$Petal.Area = mapply(tri_area , iris$Petal.Length , iris$Petal.Width )


# This is the document where I learn introductory R.
#January 5, 2016 by Robyn J Burnham
dist10 <--rnorm(10)
x<-1 #
# start lines with hashes to separate sections
y<-x*x
z<-y*y   # this would not execute

x+y+z #
mass <- 47.5
age <- 122
mass <- mass * 2.3
age <- age - 20
ratio<-mass/age
as.logical(answer)
logical(length=10)
as.logical(answer)
answer<-TRUE
is.logical(answer)
height<-15
typeof(height)
dog_name<-'Puppy'
typeof(dog_name)

xx <- c(1.7, "a")
as.numericxx <- c(TRUE, 2)
xx <- c("a", TRUE)


# {
# 	'created_on' : '3 May 2017',
# 	'aim_of_rscript' : 'using vectors in R',
# 	'coded_by' : 'Rishikesh Agrawani',
# }

#creating a vector for even numbers
evens.vector <- c(2,4,8,10,0,44) #evensVector is Ok but I am following Google naming convention
print(evens.vector)

#creating a vector for cities
cities.vector <- c("Bangalore", "Raipur", "Dhamtari", "Jagdalpur")
print(cities.vector)

##################### OUTPUT ##########################
# [1]  2  4  8 10  0 44
# [1] "Bangalore" "Raipur"    "Dhamtari"  "Jagdalpur"


# Get the command line arguments
args <- commandArgs()

options(warn=1)

# Assign the ranges to mybegin and myend
mybegin <- as.integer(1)
myend <- as.integer(10)

cat("number(x)          Sqr(x)\n")
cat("------------------ ----------\n")
for (i in mybegin:myend) {
        cat(i,"                ",i*i,"\n")
}
q()


# Getting help on a function (seq - functionname)
?seq
help(seq)
# Run all the R code from the Examples part of R's online help topic
example(seq)

# demo is a user-friendly interface to running some demonstration R scripts.
# demo() gives the list of available topics.
demo()

# Allows for searching the help system for documentation matching
# a given character string in the (file) name, alias, title, concept
# or keyword entries (or any combination thereof), using either fuzzy
# matching or regular expression matching. Names and titles of the
# matched help entries are displayed nicely formatted.
??"multivariate normal"
help.search("multivariate normal")

# help for loop
?for

#
?Startup

?files


no=c(1:3)
name=c("Monu","Himanshu","Palash")
marks=c(75,76,77)
dframe=data.frame(no,name,marks)
dframe

colnames=names(dframe)
colnames

for (i in dframe)
  {
  classc=class(i)
  print(classc)
}


# ifキソ

nums1 <- c(10,20,30)

# }の行にelseを書かないとコンパイルエラーになるので注意
if ( mean(nums1) < 15 ) {
	print("mean(nums1)<15 !")
} else if( mean(nums1) < 25 ) {
	print("mean(nums1)<25 !")
} else {
	print("mean(nums1)>=25 !")
}

# 等しいと等しくない
nums2 <- c(40,50,60)
nums3 <- c(70,80)
if( length(nums1) == length(nums2) ){
	print("true")
}
if( length(nums1) != length(nums3) ){
	print("true")
}

# andとor
if( (1<2) && (3<4) ){
	print("true")
}
if( (1<2) || (3>4) ){
	print("true")
}


# variable can use following ways

varaible1 <- 23
variable.first <- 345
variable_second <- 545

# use print to display or run the above example.
print(varaible1)
print(variable.first)
print(variable_second)

# variable cannot be started by digit followed by period(.) and underscore(_)

.1Variable   # Not true
_2Variable   # Not true

# cannot use reserved word

if,else,repeat,while,function etc..


# patient-count

# count patients when more than one row per patient

library(tidyverse) #for packages dplyr

# create a small example dataframe
df1 <- data_frame( patient = c(1,1,2,2,2,3),
                   diagnosis = c('lymph','B','C','D','E','lymph'))

# patients
patients <- unique(df1$patient)
#does the same
#patients <- unique(df1['patient'])

# number of patients
length(patients)
# 3

# beware that length gives the length of a vector
# length also gives the number of columns in a datframe
# to get the number of rows in a dataframe use nrow()
length(df1)
nrow(df1)


#####################################################################################
#                                                                                #
# TITLE: Building Health State Transition Models in R: Chapter 3.2                  #
#                                                                                #
# DESCRIPTION: In this section, we explore creating some simple objects in R        #
#                                                                                #
# AUTHOR: Ian Cromwell                                                              #
#                                                                                #
# DATE: January, 2020                                                               #
#                                                                                #
#####################################################################################

test <- 100
test

test_2 <- sample(0:10, 5, replace=T)
test_2

test + test_2
test*test_2
test/test_2

test_3 <- test + test_2
test_3

c(test, test_2)
c(test_2, test)


#function declaration
say.hello <- function(){
    print("Hello, World!")
}

say.hello()

sprintf("Hello, %s", "Boss")
sprintf("Hello, %s, today is %s", "Boss", "Sunday")

#function declaration with a parameter
hello.person <- function(name){
    print(sprintf("Hello, %s", name))
}

hello.person("Minnie")

#indefinite number of parameters
hello.person <- function(first, last="Doe"){
    print(sprintf("Hello, %s %s", first, last))
}

hello.person("Minnie", "Mouse")

#unlabeled param using ...
hello.person <- function(first, last="Doe", ...){
    print(sprintf("Hello %s %s", first, last))
}

hello.person("Mickey", "Mouse", extra="goodbye")

double.num <- function(x){
    return(x * 2)
    print("Hello")
    return(17)
}

double.num(3)

fib <- function(n){
    if (n == 1){
        return(1)
    } else if (n ==2){
        return(1)
    } else {
        return (fib(n-1) + fib(n-2))
    }
}

fib(8)

use.switch <- function(x){
    switch(x,
           "a"="first",
           "b"="second",
           "z"="last",
           "c"="third",
           "other")
}

x <- 1
y <- 2
ifelse(x == 1 & y == 3, "Yes", "No")

#For loops
states <- c("California", "North Carolina", "Nebraska", "Oklahoma",
            "Missouri", "Virginia", "New York")
statesLength <- rep(NA, length(states))
names(statesLength) <- states
for (i in states){
    statesLength[i] <- nchar(i)
}

# but better is to vectorize
statesLength <- nchar(states)
names(statesLength) <- states

#while loop
x <- 1
while (x <= 5){
    print(x)
    x <- x + 1
}

#also have next and break


# (2) #########

print("Do a very simple parallel loop")
##
#ct <- create_cluster(cores)
ct <- makeCluster(cores)
registerDoParallel(ct)
##

nt<-10
asum=0
foreach(ijk=1:nt ) %dopar% {
	asum<-asum+ijk
}
print(asum)

print("What happened?")

stopCluster(ct)
#readline(prompt = "NEXT>")


# Limit output of data frame output to 10 lines
options(repr.matrix.max.rows = 10)

add_two_numbers <- function(x, y) {
  x + y
}

add_two_numbers(1, 4)

math_two_numbers <- function(x, y, operation) {
  if (operation == "add") {
    return(x + y)
  }
  x - y
}

math_two_numbers (1, 4, "add")

math_two_numbers (1, 4, "subtract")

math_two_numbers <- function(x, y, operation = "add") {
  if (operation == "add") {
    return(x + y)
  }
  x - y
}

math_two_numbers (1, 4)

math_two_numbers (1, 4, "subtract")

add <- function(x, y, ...) {
    print(list(...))
}
add(1, 3, 5, 6)

x <- 10

add_to_x <- function(to_add) {
    x <- 5
    to_add + x
}

add_to_x(2)

x <- 10

add_to_x <- function(to_add) {
    to_add + x
}

add_to_x(2)

add_to_x <- function(to_add) {
    to_add + x
}

x <- 10
add_to_x(2)

x <- 20
add_to_x(2)

x <- 10

add_to_x <- function(to_add) {
    x <- to_add + x
    x
}

add_to_x(2)
add_to_x(2)
add_to_x(2)

dplyr::select(mtcars, mpg, cyl, hp, qsec)

fahr_to_celsius <- function(temp) {
  (temp - 32) * 5/9
}

fahr_to_celsius <- function(temp) {
  if(!is.numeric(temp)) {
    stop("`fahr_to_celsius` expects a vector of numeric values")
  }
  (temp - 32) * 5/9
}

library(tidyverse)
library(gapminder)

gapminder |>
  filter(country == "Canada", year == 1952)

gapminder[gapminder$country == "Canada" & gapminder$year == 1952, ]

filter_gap <- function(col, val) {
  filter(gapminder, {{col}} == val)
}

filter_gap(country, "Canada")

group_summary <- function(data, group, col, fun) {
  data |>
    group_by({{ group }}) |>
    summarise( {{ col }} := fun({{ col }}))
}

group_summary(gapminder, continent, gdpPercap, mean)

#' Converts temperatures from Fahrenheit to Celsius.
#'
#' @param temp a vector of temperatures in Fahrenheit
#'
#' @return a vector of temperatures in Celsius
#'
#' @examples
#' fahr_to_celcius(-20)
fahr_to_celsius <- function(temp) {
    (temp - 32) * 5/9
}

#' Count class observations
#'
#' Creates a new data frame with two columns,
#' listing the classes present in the input data frame,
#' and the number of observations for each class.
#'
#' @param data_frame A data frame or data frame extension (e.g. a tibble).
#' @param class_col unquoted column name of column containing class labels
#'
#' @return A data frame with two columns.
#'   The first column (named class) lists the classes from the input data frame.
#'   The second column (named count) lists the number of observations for each class from the input data frame.
#'   It will have one row for each class present in input data frame.
#'
#' @export
#'
#' @examples
#' count_classes(mtcars, am)
count_classes <- function(data_frame, class_col) {
  # returns a data frame with two columns: class and count
}

library(testthat)

test_that("`count_classes` should return a data frame or data frame extension", {
  # tests to be added here
})

test_that("`count_classes` should return a data frame, or data frame extension,
with the number of rows that corresponds to the number of unique classes
in the column passed to `class_col`", {
  # tests to be added here
})

test_that("`count_classes` should return a data frame, or data frame extension,
whose values in the `count` column correspond to the number of observations
for the group in the `class` column from the original data frame", {
  # tests to be added here
})

test_that("`count_classes` should throw an error when incorrect types
are passed to `data_frame` and `class_col` arguments", {
  # tests to be added here
})

# function input for tests
five_classes_3_obs <- data.frame(class_lables = rep(c("class1", "class2", "class3", "class4", "class5"), 3))
two_classes_3_obs <- data.frame(class_lables = rep(c("class1", "class2"), 3))
two_classes_3_and_2_obs <- data.frame(class_lables = c(rep(c("class1", "class2"), 2), "class1"))
two_classes_3_and_1_obs <- data.frame(class_lables = c(rep("class1", 3), "class2"))
one_class_3_obs <- data.frame(class_lables = rep("class1", 3))
empty_df  <- data.frame(class_lables = character(0))
vector_class_labels <- rep(c("class1", "class2"), 3)
two_classes_3_obs_as_list <- list(class_lables = rep(c("class1", "class2"), 3))

# expected function output
five_classes_3_obs_output <- data.frame(class = c("class1", "class2", "class3", "class4", "class5"),
                                        count = rep(3, 5))
two_classes_3_obs_output <- data.frame(class = c("class1", "class2"),
                                count = c(3, 3))
two_classes_3_and_2_obs_output <- data.frame(class = c("class1", "class2"),
                                      count = c(3, 2))
two_classes_3_and_1_obs_output <- data.frame(class = c("class1", "class2"),
                                      count = c(3, 1))
one_class_3_obs_output <- data.frame(class = "class1",
                              count = 3)
empty_df_output <- data.frame(class = character(0),
                              count = numeric(0))

test_that("`count_classes` should return a tibble", {
  expect_s3_class(count_classes(two_classes_3_obs, class_lables), "tibble")
})

test_that("`count_classes` should return a data frame, or data frame extension,
with the number of rows that corresponds to the number of unique classes
in the column passed to `class_col`", {
  expect_equivalent(count_classes(five_classes_3_obs, class_lables), five_classes_3_obs_output)
  expect_equivalent(count_classes(two_classes_3_obs, class_lables), two_classes_3_obs_output)
  expect_equivalent(count_classes(one_class_3_obs, class_lables), one_class_3_obs_output)
  expect_equivalent(count_classes(empty_df, class_lables), empty_df_output)
})

test_that("`count_classes` should return a data frame, or data frame extension,
whose values in the `count` column correspond to the number of observations
for the group in the `class` column from the original data frame", {
  expect_equivalent(count_classes(two_classes_3_and_2_obs, class_lables), two_classes_3_and_2_obs_output)
  expect_equivalent(count_classes(two_classes_3_and_1_obs, class_lables), two_classes_3_and_1_obs_output)
})

test_that("`count_classes` should throw an error when incorrect types
are passed to `data_frame` and `class_col` arguments", {
  expect_error(count_classes(two_classes_3_obs, vector_class_labels))
  expect_error(count_classes(two_classes_3_obs_as_list, class_lables))
})

#' Count class observations
#'
#' Creates a new data frame with two columns,
#' listing the classes present in the input data frame,
#' and the number of observations for each class.
#'
#' @param data_frame A data frame or data frame extension (e.g. a tibble).
#' @param class_col unquoted column name of column containing class labels
#'
#' @return A data frame with two columns.
#'   The first column (named class) lists the classes from the input data frame.
#'   The second column (named count) lists the number of observations for each class from the input data frame.
#'   It will have one row for each class present in input data frame.
#'
#' @export
#'
#' @examples
#' count_classes(mtcars, am)
count_classes <- function(data_frame, class_col) {
  if (!is.data.frame(data_frame)) {
    stop("`data_frame` should be a data frame or data frame extension (e.g. a tibble)")
  }

  data_frame |>
    dplyr::group_by({{ class_col }}) |>
    dplyr::summarize(count = dplyr::n()) |>
    dplyr::rename_at(1, ~ "class")
}

test_that("`count_classes` should return a tibble", {
  expect_s3_class(count_classes(two_classes_3_obs, class_lables), "data.frame")
})

test_that("`count_classes` should return a data frame, or data frame extension,
with the number of rows that corresponds to the number of unique classes
in the column passed to `class_col`", {
  expect_equivalent(count_classes(five_classes_3_obs, class_lables), five_classes_3_obs_output)
  expect_equivalent(count_classes(two_classes_3_obs, class_lables), two_classes_3_obs_output)
  expect_equivalent(count_classes(one_class_3_obs, class_lables), one_class_3_obs_output)
  expect_equivalent(count_classes(empty_df, class_lables), empty_df_output)
})

test_that("`count_classes` should return a data frame, or data frame extension,
whose values in the `count` column correspond to the number of observations
for the group in the `class` column from the original data frame", {
  expect_equivalent(count_classes(two_classes_3_and_2_obs, class_lables), two_classes_3_and_2_obs_output)
  expect_equivalent(count_classes(two_classes_3_and_1_obs, class_lables), two_classes_3_and_1_obs_output)
})

test_that("`count_classes` should throw an error when incorrect types
are passed to `data_frame` and `class_col` arguments", {
  expect_error(count_classes(two_classes_3_obs, vector_class_labels))
  expect_error(count_classes(two_classes_3_obs_as_list, class_lables))
})

options(repr.plot.width = 4, repr.plot.height = 4)

cars_ggplot_scatter <- ggplot2::ggplot(mtcars, ggplot2::aes(hp, mpg)) +
    ggplot2::geom_point()

cars_ggplot_scatter

cars_ggplot_scatter$layers[[1]]$geom

cars_ggplot_scatter$mapping$x

#' scatter2d
#'
#' A short-cut function for creating 2 dimensional scatterplots via ggplot2.
#'
#' @param data data.frame or tibble
#' @param x unquoted column name to plot on the x-axis from data data.frame or tibble
#' @param y unquoted column name to plot on the y-axis from data data.frame or tibble
#'
#' @return
#' @export
#'
#' @examples
#' scatter2d(mtcars, hp, mpg)
scatter2d <- function(data, x, y) {
    ggplot2::ggplot(data, ggplot2::aes(x = {{x}}, y = {{y}})) +
        ggplot2::geom_point()
}

helper_data <- dplyr::tibble(x_vals = c(2, 4, 6),
                   y_vals = c(2, 4, 6))

helper_plot2d <- scatter2d(helper_data, x_vals, y_vals)

test_that('Plot should use geom_point and map x to x-axis, and y to y-axis.', {
    expect_true("GeomPoint" %in% c(class(helper_plot2d$layers[[1]]$geom)))
    expect_true("x_vals"  == rlang::get_expr(helper_plot2d$mapping$x))
    expect_true("y_vals" == rlang::get_expr(helper_plot2d$mapping$y))
})

cars_scatter <- plot(mtcars$hp, mtcars$mpg)

typeof(cars_scatter)
class(cars_scatter)

pretty_scatter <- function(.data, x_axis_col, y_axis_col) {
    ggplot2::ggplot(data = .data,
                    ggplot2::aes(x = {{ x_axis_col }}, y = {{ y_axis_col }})) +
        ggplot2::geom_point(alpha = 0.8, colour = "steelblue", size = 3) +
        ggplot2::theme_bw() +
        ggplot2::theme(text = ggplot2::element_text(size = 14))
}

library(palmerpenguins)
library(ggplot2)
penguins_scatter <- pretty_scatter(penguins, bill_length_mm, bill_depth_mm) +
    labs(x = "Bill length (mm)", y = "Bill depth (mm)")
penguins_scatter


#item a
for(i in seq(1, 50)) {
  cat(i, ", ", sep="")
}

#item b
i <- 1
while(i <= 1024) {
  cat(i, ", ", sep="")
  i = i * 2
}


# diagnosis-count

### count number of unique diagnoses

library(tidyverse) #for packages dplyr

# create a small example dataframe with just one column
df1 <- data_frame( diagnosis = c('Hodgkins Lymphoma','other','Hodgkins','Lymphoma','Lymphoma'))

# patients
diagnoses <- unique(df1$diagnosis)
#does the same
#diagnoses <- unique(df1['diagnosis'])

# number of diagnoses
length(diagnoses)

# beware that length gives the length of a vector
# length also gives the number of columns in a dataframe
# to get the number of rows in a dataframe use nrow()
length(df1)
nrow(df1)


# Working with lapply function

# lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
# lapply(x, FUN)
# x: element to review
# FUN: function to apply to element(s)

# 1. Perform initial review
# The vector pioneers has already been created for you
pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")

# Split names from birth year
split_math <- strsplit(pioneers, split = ":")

# Convert to lowercase strings: split_low
split_low <- lapply(split_math, tolower)

# Take a look at the structure of split_low
str(split_low)

# 2. Extract elements from the vector with two functions
# Code from previous exercise:
pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")
split <- strsplit(pioneers, split = ":")
split_low <- lapply(split, tolower)

# Write function select_first()
select_first <- function(x) {
  x[1]
}

# Apply select_first() over split_low: names
names <- lapply(split_low, select_first)

# Write function select_second()
select_second <- function(x) {
  x[2]
}

# Apply select_second() over split_low: years
years <- lapply(split_low, select_second)

# 3. Create and use anonymous function i.e. function not assigned to a variable
# split_low has been created for you
split_low

# Transform: use anonymous function inside lapply
function(x) {x[1]}
names <- lapply(split_low, function(x) {x[1]})

# Transform: use anonymous function inside lapply
function(x) {x[2]}
years <- lapply(split_low, function(x) {x[2]})

# 4. Use lapply with additional arguments - allows the creation of a generic function to be applied multiple times
# Definition of split_low
pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857")
split <- strsplit(pioneers, split = ":")
split_low <- lapply(split, tolower)

# Generic select function
select_el <- function(x, index) {
  x[index]
}

# Use lapply() twice on split_low: names and years
names <- lapply(split_low, select_el, index = 1)
years <- lapply(split_low, select_el, index = 2)


#' Making the shape file thin
#'
#' This function helps you thin the data to avoid crashing your R session for very large shape files
#'
#'
#' @param x A shape file
#' @param tolerance the value used for thinning the polygon (default=0.1)
#' @import rmapshaper
#' @export
#' @return It returns a thinned data frame regarding the original shape file
#' @examples
#' data("Iran")
#' dframe <- thin(Iran)
#'
thin <- function(x, tolerance = 0.1){
  rmapshaper::ms_simplify(x, snap_interval = tolerance)
}


# Results are system dependent
num <- c(1, 3, 6, 10)
object.size(num)  # e.g. 56 bytes

#Allocating vectors using ':' results in less memory being (reportedly) used
num2 <- 1:4
object.size(num2) # e.g. 40 bytes

#Memory shared by objects isn't always counted
l <- list(a=c(1, 3, 6, 10), b=1:4)
object.size(l)    # e.g. 280 bytes

l2 <- list(num, num2)
object.size(l2)   # e.g. 128 bytes


# loading the dslabs package and the murders dataset
library(dslabs)
data(murders)

# determining that the murders dataset is of the "data frame" class
class(murders)

# finding out more about the structure of the object
str(murders)

# showing the first 6 lines of the dataset
head(murders)

# using the accessor operator to obtain the population column
murders$population

# displaying the variable names in the murders dataset
names(murders)

# determining how many entries are in a vector
pop <- murders$population
length(pop)

# vectors can be of class numeric and character
class(pop)
class(murders$state)

# logical vectors are either TRUE or FALSE
z <- 3 == 2
z
class(z)

# factors are another type of class
class(murders$region)

# obtaining the levels of a factor
levels(murders$region)
name(murders)


#
# Exemplo 2
#

# Atribuição de valores para variáveis x1 e x2
x1 <- 0.003815
x2 <- 1234567890
# Realiza o mesmo cálculo do Exemplo 1 atribuindo o
# valor do resultado para a variável resultado1
resultado1 <- (x1 + x2) - x2
resultado1
# Realize o segundo cálculo do Exemplo 1 atribuindo
# o valor do resultado para a variável resultado2
resultado2 <- x1 + (x2 - x2)
resultado2


library("dplyr")

cleanData <- function(yourData){

  df = yourData
  df = select_if(yourData, is.numeric)
  df[complete.cases(df), ]
  return(df)
}


# Data Wrangling in R
# 4.2 Making Wide Datasets Long with gather()
#

# Load the tidyverse
library(tidyverse)

# Read in the Pew dataset
pew <- read_csv("http://594442.youcanlearnit.net/pew.csv")

# Let's take a look at what we have
pew

# This looks to be a gathering problem.  Our dataset is wide and we want it to be long.
# The gather function can take care of that for us
pew.long <- gather(pew, income, freq, -religion)

# And what did we get?
pew.long


for(i in 0:4) {
  s <- ""
  for(j in 0:i) {
    s <- paste(s, "*", sep="")
  }
  print(s)
}


#Syntax de if
x <- 3
if(x>3){
  y <- 10
} else{
  y <- 0
}
print(x,y)

# Syntax for

require()

?set.seed
?sample

require("")
# Functions

f <- function(a=1, b=2){
  return (a^2)
}

args(f)

set.seed(2)
rnorm(5)
?split
?gl
?apply