











Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!












Radice quadrata: sqrt(16)
Logaritmo: log(valore, base)
e^x: exp(x)
coseno: cos(x)
o pi greco: pi
seno: sin(x)
tangente: tan(x)
valore assoluto: abs(x)
fattoriale: factorial(x)
: choose(10, 4)
Creare una funzione: g<-function(var1,var2) {var1+var2}
o w31<-g(8,9)
o my_func <- function(){
print('hello')
my_func
rappresentare una data: x <- as.Date("1971-01-01")
o unclass(x)
o typeof(x)
o attributes(x)
Rimuovi elementi: rm(i)
Rimuovi lista: rm(list=ls())
Crea lista: L <- list(x,y,z)
o x_named <- list(a = 1, b = 2, c = 3)
o z <- list(list(1, 2), list(3, 4))
estrai elementi da lista:
o a <- list(a = 1:3, b = "a string", c = pi, d = list(-1, -5))
o str(a[1:2])
o str(a[[1]]) #It removes a level of hierarchy from the list
Rimuove oggetti che contengono “V”: rm(list=ls(pat="V"))
apri lista: ls()
incolla elementi: paste("A","B",2,"c",sep="*")
comando which: which(x<2) which((x >= -1) & (x < 5)) which((x < -2) | (x > 1))
indici degli elementi che soddisfano una certa condizione: index <- which((x >= -1) & (x < 5))
string: string <- c("gianni", "luca", "fabio")
bool: bool <- c(TRUE, TRUE, FALSE, FALSE, FALSE)
lista: elle <- list(CPLX = cmp, NOMI = string, BOOL = bool, matrice = A)
o accedere agli elementi: elle$BOOL elle[[3]]
o elle["NOMI"] (lista) elle[["NOMI"]] (vettore)
o struttura di un oggetto: str(elle)
data frame: data.frame( )
o data(iris)
o View(iris)
o edit(iris)
o str(iris)
o iris$Species
export a data frame in my pc: write.table( )
to import a data frame from pc to rstudio: read.delim( )
o if the file is from excel: read.excel( )
o if the file is from .csv: read_csv("heights.csv")
creare un sub-environment:
o e1 <- new.env()
o e1$a <- 10
assign("b", 3, env=e1)
o e1$a
o ls()
o ls(e1)
local e global environment:
o eval(expression(a+b),envir=e1)
o e
o str(e1)
o x <- 4 #will be assigned to the global env
o assign("x", get("a",e1)+get("b",e1), e1) #local env
o ls(e1)
o e1$x
accedere al global environment:
o .GlobalEnv
o str(.GlobalEnv)
piazzare una funzione in global vs local environment
o myf <- function(u) u+a
o myf(5)
o environment(myf) <- e
o myf(5)
classi di oggetti:
o w1<-
o class(w1)
check the type of an element:
o typeof(letters)
o typeof(1:10)
vettore: y <- c(2,7,4,1) x <- -1:3 z <- seq( ) k <- rep( )
o naming them: c(x = 1, y = 2, z = 4)
library(purrr)
#There are three very important attributes that are used to implement
fundamental parts of R:
#1. "Names" are used to name the elements of a vector
#2. "Dimensions" make a vector behave like a matrix or array
#3. "Class" is used to implement the S3 object oriented system
curve(2x^2 + 3x + 4, from=-2, to=3, add=TRUE/FALSE)
o title("Square root")
o to divide the space for more of these functions: par(mfrow=c(2,2))
plot(tp1, split= c(1, 1, 1, 2)
o 1, 1: position on the x and y axes (this will be the first quadrant)
o 1, 2: how to divide each axis (I will have x in 1 and y split in 2)
oppure
persp(x,y,z, xlab="X", ylab="Y", zlab="Z")
somma <- function(a=1,b) {
if( b>0 )
a+b
else
print("error")
o somma(2,3)
o somma(b=3)
for: for(i in 1:9){
assign(paste("V",i,sep=""), i)
x <- 0
for(i in 1:10){
x <- x + i
x <- 0
while(x < 10){
x <- x+
x <- 4
if(x>=0){
sqrt(x)
if (test_expression) {
statement
} else {
statement
Consider the first 100 digits and draw a random sample (without replacement) of
14 elements. Use the if/else or the ifelse statements to show which elements are odds
and which are even
x <- c(1:100)
y <- sample(x,14,replace=FALSE)
z <-ifelse(y%%2==0,"EVEN","ODDS")
In a ballot there are 7 white balls and 3 black balls. We draw “in block” (i.e.,
without replacement) 4 balls. The experiment consists of evaluating how many
white balls have been drawn. Use a for loop to repeat this experiment 1,
times.
ballot <- c(rep("White",7),rep("Black",3))
nrep <- 1000
out <- rep(NA,nrep)
for (i in 1:nrep)
x <- sample(ballot,4,replace=FALSE)
y <- sum(x == "White")
out[i] <- y
out
table(out)
In this experiment a regular coin is flipped for 1 million times. Perform this
experiment using:
a) The sample function;
b) A for loop
c) and use the system.time function to compare the times of execution for (a)
and (b). Express your results both in absolute and in relative terms.
coin <- c("heads","tails")
nrep <- 1000000
st.1 <- system.time(x <- sample(coin,nrep,replace=TRUE))
st.2 <- system.time(
x <- rep(NA,nrep)
for (i in 1:nrep) x[i] <- sample(coin,1)
st.
st.
st.2[3] - st.1[3]
st.2[3] / st.1[3]
somma <- function(a=1,b) {
if( b>0 )
a+b
else
Doppia distribuzione: table(X,Y) table(X, cut(W,br=classes)) table(X,Y,Z)
Distribuzione marginale di X: margin.table(tab,1)
Distribuzione marginale di Y: margin.table(tab,2)
Frequenza relativa congiunta: prop.table(table(X,Y))
Frequenza condizionata di Y dato X: prop.table(tab,1)
Frequenza condizionata di X dato Y: prop.table(tab,2)
Istogrammi: hist(W, breaks=classes) hist(W, breaks=3) (tre classi) hist(W,
breaks="ST") (classi automatiche)
Bar plot: barplot(table(X))
Stick plot: plot(table(Z))
Pie chart: pie(table(Y)) pie(table(Y), density=15, angle=15+10*(1:4), col=1:4)
Bubble plot (distribuzione di una variabile comparata a un’altra): bubbleplot(table(X,Y))
Scatter plot: plot(Z,W)
Boxplot: boxplot(W)
Interpolazione dell’istogramma con poligono di frequenza:
o hist.pf <- function(x, br, ...){
if(missing(br)) # there is no value for "br"
ist <- hist(x,...)
else
ist <- hist(x, breaks=br,...)
if(ist$equidist)
lines( c(min(ist$breaks),ist$mids,max(ist$breaks)),
c(0,ist$counts,0))
else
lines( c(min(ist$breaks),ist$mids,max(ist$breaks)),
c(0,ist$intensities,0))
hist.pf(W)
Kernel density estimation (optimal bandwidth): plot(density(W))
Kernel density estimation (fixed bandwidth): plot(density(W,bw=3))
o density(W)
library(stepfun)
Empirical Cumulative Distribution Function: plot(ecdf(Z))
o ecdf(z)(2)
qqplot:
o qqnorm(W)
qqline(W)
o ggplot (nyfs1, aes (sample = sqrt (waist.circ))) +
geom_point (stat="qq", color = "purple") +
labs (y = "Ordered Square root of Waist Circumference",
title="Normal Q-Q plot of Square Root of Waist
Circumference")
riassunto di elementi: summary(X) summary(table(X,Y))
mediana: median(W)
quantile: quantile(W, c(0.1,0.3,0.7,0.93,.98))
varianza: var(W)
correlazione: cor(Z,W,method='pearson') cor(Z,W,method='spearman')
standard deviation: sd(W)
Use R to write your own function of kurtosis following the definition. Then,
consider the following vectors: Show the distribution of your data using a
boxplot. Then, apply your own function (previously created) to calculate the
kurtosis of the distribution of x and y.
kurt <-function(x){
n <- length(x)
s4 <- sqrt(var(x)*(n-1)/n)^
mx <- mean(x)
kt <- sum((x-mx)^4)/s
kt/n
boxplot(x,y, names=c("x","y"))
kurt(x)
kurt(y)
Review on the books or using the web the concept of skewness of a distribution.
Use R to write your own function of skewness. Then, calculate the skewness for
the distribution of x and y.
skew <- function(x){
n <- length(x)
s3 <- sqrt(var(x)*(n-1)/n)^
mx <- mean(x)
sk <- sum((x-mx)^3)/s
sk/n
skew(x)
skew(y)
Use R to randomly extract:
Apply your own functions previously created to calculate skewness and kurtosis
of v1, v2, v3.
v1 <- rnorm(20,0,3)
v
v2 <- rlnorm(20,0,3)
v
v3 <- rbeta(20,1,1)
v
skew(v1)
skew(v2)
skew(v3)
kurt(v1)
kurt(v2)
kurt(v3)
Open in R the already built-in dataset “Titanic”.
edit(cars)
str(cars)
plot(cars) -> POINT 2
Transformation -> POINT 3:
attach(cars)
plot(speed,sqrt(dist))
cor(speed,sqrt(dist))
summary(lm(sqrt(dist) ~ speed))
calculate correlation -> POINT 4:
attach(cars)
cor(dist, speed)
detach(cars)
cor(cars$dist, cars$speed, method="pearson/spearman")
estimate the model -> POINT 5 AND 6:
model <- lm(dist ~ speed, data=cars) y=dist; x=speed
summary(model)
gasB <- lm(Gas ~ Temp, whiteside, subset = Insul=="Before") #Y IS GAS HERE
gasA <- lm(Gas ~ Temp, whiteside, subset = Insul=="After") #Since we have two different
moments of insulation, we use subset to analyse them separately, this way we see the
effect of the intervention on insulation
f3 <- ols(medv~., data = Boston) #regression with y=medv and xi=all the other vars of the
dataset
explore the residuals -> POINT 7:
plot(model) shows graphs and diagnostics about the model
If residuals are negative: the model underestimates
If residuals are positive: the model overestimates
plot(model$res) shows the residuals
res3 = mod3$residuals
ycapp = mod3$fitted.values
plot(ycapp, res3, lwd=2,main='Residuals vs fitted')
abline(h=0, lwd=2)
qqnorm(res3, datax=T)
res.ord = sort(res3)
regression line on a graph -> POINT 8:
plot(cars)
abline(model)
resid(gasA) #Models residuals
hist(resid(gasA)) #Histogram of residuals
predicted values -> POINT 9:
predict(model) #Predicted values of the regression line
predict(model, newdata=data.frame(speed=9)) #Predicted value for speed=
predict(model, newdata=data.frame(speed=c(9,2,13))) #Predicted value for speed=9,2,
confidence bandwiths :
pc <- predict(model,interval="c")
pc
attach(cars)
plot(speed,dist)
abline(model)
matlines(speed,pc[,2:3],lty=3:3,col="red",lwd=2:2) #Graph of the confidence bandwidths
detach(cars)
extract random values from a random variable :
to fix the random generation i must run this set.seed together with the runif command; if i
put four different numbers again it is gonna generate a new random value:
set.seed(1234)
uniform r.v.: x1 <- runif(50)
i'll get the cos of the sin transformation of my random unif: x2 <- cos(sin(runif(50)))
binom r.v.: rbinom(10, 20, 0.4) #10=x; 20=n; 0.4=p
poisson r.v.: rpois(30, 4)
norm r.v.: x3 <- rnorm(50,sd=45) #RNORM(N=OBSERVATIONS; MEAN=MEDIA(0);
dnorm to see the density
pnorm for probability function
qnorm if i want a quantile
chisq r.v.: rchisq(50,df=1)
t-student r.v.: x5 <- rt(50, df=3)
we could create a function with a random component and then create a linear regression model
with it :
y <- 4 + 2*x1 - x2 + rnorm(50)
lm(y ~ x1 + x2)
summary(lm(y ~ x1 + x2))
sample elements from a vector :
x <- 1:
sample(x,3) #without repetition
sample(x,11,rep=TRUE) #with repetition
library(lattice)
library(mlmRev)
Istogramma:
o histogram( ~ gcsescore | factor(score), data = Chem97,main="GCSE score by score")
Grafico di densità:
o densityplot( ~ gcsescore | factor(score), data = Chem97, ref = TRUE, plot.points=F)
o densityplot( ~ gcsescore, data = Chem97, groups=score,
plot.points=F, ref=TRUE, auto.key=list(columns=3, title="score"))
layout diverso:
o densityplot( ~ gcsescore | factor(score), data = Chem97, ref = TRUE ,
plot.points=F, layout=c(1,6), main="GCSE score by score")
plot
view(iris)
o xyplot(Sepal.Length ~ Petal.Length | Species, data=iris)
#in versicular and virginica there is more variability than in the setosa, also, unlike
the setosa,
#There could be a linear relation between Sepal lght and Petal lgth for versicolar and
virginica
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv))
o ggplot(data = mpg) +
geom_smooth(
mapping = aes(x = displ, y = hwy, color = drv),
show.legend = FALSE
Per avere diverse geometrie in un solo grafico:
o ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(x = displ, y = hwy))
Bar chart:
o ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut))
o ggplot(data = diamonds) +
stat_count(mapping = aes(x = cut))
cambiamenti estetici del bar chart:
o gplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, colour = cut))
o ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = cut))
dividere il bar chart per classi:
o ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity))
o ggplot(data = diamonds, mapping = aes(x = cut, fill = clarity)) +
geom_bar(alpha = 1/5, position = "identity")
o ggplot(data = diamonds, mapping = aes(x = cut, colour = clarity)) +
geom_bar(fill = NA, position = "identity")
o ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity), position = "fill")
o ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
box plot:
vertical:
o ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot()
horizontal:
o ggplot(data = mpg, mapping = aes(x = class, y = hwy)) +
geom_boxplot() +
coord_flip()
to filter for a qualitative variable:
o ggplot(data = merged) +
geom_boxplot(mapping = aes(x = reorder(Sex.f,DigScore, FUN = median),
y = DigScore),col="orange")+
labs(x="Gender",y="Digital score")
#coord_quickmap() sets the aspect ratio correctly for maps.
#This is very important if you are plotting spatial data with ggplot
o nz <- map_data("nz")
o ggplot(nz, aes(long, lat, group = group)) +
geom_polygon(fill = "white", colour = "black")
o ggplot(nz, aes(long, lat, group = group)) +
geom_polygon(fill = "white", colour = "black") +
coord_quickmap()
#coord_polar() uses polar coordinates
o bar <- ggplot(data = diamonds) +
geom_bar(
mapping = aes(x = cut, fill = cut),
show.legend = FALSE,
width = 1
theme(aspect.ratio = 1) +
labs(x = NULL, y = NULL)
o bar
o bar + coord_flip()
o bar + coord_polar()
o ggplot(mpg, aes(x = factor(1), fill = drv)) +
geom_bar(width = 1) +
coord_polar(theta = "y") #FOR PIE CHART
#line chart:
geom_line()
#boxplot:
geom_boxplot()
#histogram:
geom_histogram()
#area chart:
geom_area()
Adds a small amount of noise from the observations:
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy), position = "jitter")
geom_count:
ggplot(data = diamonds) +
geom_count(mapping = aes(x = cut, y = color))
geom_tile:
diamonds %>%
count(color, cut) %>%
ggplot(mapping = aes(x = color, y = cut)) +
geom_tile(mapping = aes(fill = n))
geom_freqpoly:
ggplot(data = diamonds, mapping = aes(x = price)) +
geom_freqpoly(mapping = aes(colour = cut), binwidth = 500)
library(tidyverse)
Filtro:
o filter(flights, month == 1, day == 1) #It selects all flights on January 1st
Sintetizza: il data frame collassa in una singola colonna
o summarise(flights, delay = mean(dep_delay, na.rm = TRUE))
o summarise(flights, delay = mean(arr_delay, na.rm = TRUE))
o summarise(flights, delay = var(arr_delay, na.rm = TRUE))
o summarise(flights, delay = sqrt(var(dep_delay, na.rm = TRUE)))
#It can be used in combination with group_by
o by_day <- group_by(flights, year, month, day)
summarise(by_day, delay = mean(dep_delay, na.rm = TRUE))
o by_day2 <- group_by(flights, year, month)
summarise(by_day2, delay = var(arr_delay, na.rm = TRUE))
o var_arr_delay <- summarise(by_day, delay = var(arr_delay, na.rm = TRUE))
eliminare valori mancanti:
o flights %>%
o group_by(year, month, day) %>%
o summarise(mean = mean(dep_delay, na.rm = TRUE))
#For instance, imagine we want to perform
#the three following operations on the dataset:
##1. Group flights by destination
##2. Summarise to compute distance, average delay, and number of flights
##3. Filter to remove noisy points and Honolulu airport,
##4. which is almost twice as far away as the next closest airport.
#We can perform these operations using the pipe, which substantially means "then":
o delays <- flights %>%
group_by(dest) %>%
summarise(
count = n(),
dist = mean(distance, na.rm = TRUE),
delay = mean(arr_delay, na.rm = TRUE)
filter(count > 20, dest != "HNL")
delays
o flights %>%
summarise(delay = var(arr_delay, na.rm=TRUE))
Raggruppare:
#When you group by multiple variables, each summary peels off one level of the grouping.
#That makes it easy to progressively roll up a dataset:
o daily <- group_by(flights, year, month, day)
o print(per_day <- summarise(daily, flights = n()))
o print(per_month <- summarise(per_day, flights = sum(flights)))
o print(per_year <- summarise(per_month, flights = sum(flights)))
#If you need to remove grouping, and return to operations
#on ungrouped data, use ungroup()
o daily %>%
o ungroup() %>% # no longer grouped by date
o summarise(flights = n()) # all flights
#Grouping is most useful in conjunction with summarise(),
#but you can also do convenient operations with mutate() and filter():
o flights_sml %>%
group_by(year, month, day) %>%
filter(rank(desc(arr_delay)) < 10)
o my.filter <-flights_sml %>%
group_by(year, month, day) %>%
filter(rank(desc(arr_delay)) < 10)
View(my.filter)
o popular_dests <- flights %>%
group_by(dest) %>%
filter(n() > 365)
o popular_dests
o View(popular_dests)
library(tidyverse)
Creating tibbles:
From existing data.frames: as_tibble(iris)
From scratch: new.t <- tibble(
x = 1:5,
y = 1,
z = x ^ 2 + y
str(new.t)
printing tibbles:
nycflights13::flights %>%
print(n = 15, width = Inf)
viewing tibbles:
View(nycflights13::flights)
Subsetting:
df <- tibble(
x = runif(5),
y = rnorm(5)
Extract by name:
df$x
df[["x"]]
extract by position:
df[[1]]
extracting with the pipe:
df %>% .$x
#There could be a linear relation between Sepal lght and Petal lgth for versicolar and
virginica
#a st.dev could be calculated to check if our intuition was correct
o bwplot(Sepal.Length ~ Species, data=iris)
library(stringr)
fruits <- c("one apple", "two pears", "three bananas")
str_replace(fruits, c("a","e","i"), "-")
str_replace_all(fruits, c("a","e","i"), c("1","2","3"))
str_replace_all(fruits, c("one","two","three"), c("1","2","3"))
library(lubridate)
hms("7 6 5", "3-23-2", "2:23:33","Finished in 9 hours, 20 min and 4 seconds")
int1 <- interval(ymd("2001-01-01"), ymd("2002-01-01"))
int2 <- interval(ymd("2001-06-01"), ymd("2002-06-01"))
int3 <- interval(ymd("2003-01-01"), ymd("2004-01-01"))
int_overlaps(int1,int2)
int_overlaps(int1,int3)
library(foreign) #for reading and writing data stored by softwares like Minitab, S, SAS, SPSS, Stata,
Systat
write.dta(iris, iris_Stata_file <- tempfile()) #write a (temp) Stata file
read.dta(iris_Stata_file) #read a Stata file
library(rms)
set.seed(1)
x1 <- runif(200)
x2 <- sample(0:3,200,TRUE)
x2.f <- factor(x2)
x3 <- (x1 + x2/3 + rnorm(200))^
o f <- ols(sqrt(x3) ~ x1 + x2.f)
score2$Age <- cut(score2$Age, breaks = c(-Inf, median(score2$Age), +Inf), labels = c("Below
median", "Over median"))
table(score2$Age)