Document information
- University
- Politecnico di Milano
- Degree programme
- Management Engineering
- Subject
- Business Data Analys
- Material language
- Italian / English
- Classification
- Exercises · Complete set
- Original format
- Text
- Searchable text
Complete course materials for Business Data Analys in the Management Engineering degree programme at Politecnico di Milano. The document covers: 18/06/26, 14:23 esercitazione 1 esercitazione 1 2026-05-07 Esercitazione 1: Introduzione ai Dati in R 1. Approccio ad RStudio Iniziamo la nostra sessione. È buona norma iniziare sempre ripulendo l’Environment da ogni oggetto precedentemente creato (ad esempio usando
Complete course materials for Business Data Analys in the Management Engineering degree programme at Politecnico di Milano. The document covers: 18/06/26, 14:23 esercitazione 1 esercitazione 1 2026-05-07 Esercitazione 1: Introduzione ai Dati in R 1. Approccio ad RStudio Iniziamo la nostra sessione. È buona norma iniziare sempre ripulendo l’Environment da ogni oggetto precedentemente creato (ad esempio usando
Import quality: text was extracted directly from the original document.
Representative passages recognised in different parts of the material. The full extracted text remains available to search, while this compact preview makes the page easier to read.
18/06/26, 14:23 esercitazione 1 esercitazione 1 2026-05-07 Esercitazione 1: Introduzione ai Dati in R 1. Approccio ad RStudio Iniziamo la nostra sessione. È buona norma iniziare sempre ripulendo l’Environment da ogni oggetto precedentemente creato (ad esempio usando rm(list=ls()) ). # Ripulisce l'Environment rm(list = ls()) Come ogni linguaggio di programmazione che si rispetti, R è in primo luogo una calcolatrice potente e versatile. x = 2.1 # Creazione variabile numerica x y = x*exp(x)*atan(x) # Creazione variabile y facendo conti su x y # Stampo y a video ## [1] 19.31619 2. Introduzione e caricamento dei dati In R è possibile fare conti con numeri, funzioni, vettori e matrici. Tuttavia, il principale scopo del corso è Analizzare Dati, che generalmente si trovano in forma di tabelle. Passaggio FONDAMENTALE: Dire a R in quale cartella desideriamo lavorare (la Working Directory). Questo va fatto OGNI volta, perché R vede SOLO i file contenuti all’interno di questa specifica cartella. # Stampare a video la cartella di lavoro attuale: getwd() ## [1] "C:/Users/aless/OneDrive/Desktop/BDAAEsercitazioni-20260415/Esercitazione 1" # Visualizzare i File disponibili (e quindi visibili a R) dir() file:///C:/Users/aless/OneDrive/Desktop/BDAAEsercitazioni-20260415/Esercitazione 1/exsercitazione-1.html 1/15
18/06/26, 16:12 exercitaizone 3 prendo in considerazione la componenti 1 che erano quelli dei volumi totali è influenzato di più dal lazio in questo caso altro esempio: cibo se prendo in considerazione il ragruppamento i paesi in base a cio che mangiano food = read.csv('Food.txt', sep = " ") Countries = food$Country food_num = food[,2:9] # Isoliamo le variabili numeriche # È fondamentale standardizzare perché le proteine e i cereali hanno scale diverse food.sd = scale(food_num) pc.food = princomp(food.sd) eseguiamo l’analisi della varianza con lo scree plot plot(cumsum(pc.food$sdev^2)/sum(pc.food$sdev^2), type='b', xlab='Number of components', ylab='Cumulative Variance', ylim=c(0,1)) abline(h=0.8, col="red", lty=2) file:///C:/Users/aless/OneDrive/Desktop/BDAAEsercitazioni-20260415/Esercitazione 3/exsercitazione-3.html 16/26
18/06/26, 16:13 exsercitazione 6 ## ## Call: ## lm(formula = Average_Score ~ dummy + Years_Service + I(dummy * ## Years_Service), data = work) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.46452 -0.09410 -0.04348 -0.02298 0.60645 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 6.43478 0.32447 19.831 1.07e-06 *** ## dummy 0.60393 0.47713 1.266 0.25253 ## Years_Service 0.22806 0.04062 5.614 0.00136 ** ## I(dummy * Years_Service) -0.04258 0.05978 -0.712 0.50307 ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 0.4087 on 6 degrees of freedom ## Multiple R-squared: 0.8954, Adjusted R-squared: 0.843 ## F-statistic: 17.11 on 3 and 6 DF, p-value: 0.002406 # Modello ridotto (senza interazione): assumiamo che la pendenza sia uguale, cambia solo l'in tercetta model_ridotto = lm(Average_Score ~ dummy + Years_Service, data = work) summary(model_ridotto) ## ## Call: ## lm(formula = Average_Score ~ dummy + Years_Service, data = work) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.58370 -0.14853 -0.01571 0.10924 0.53311 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 6.56453 0.25888 25.357 3.79e-08 *** ## dummy 0.31832 0.24926 1.277 0.24231 ## Years_Service 0.20840 0.02874 7.252 0.00017 *** ## --- ## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 ## ## Residual standard error: 0.394 on 7 degrees of freedom ## Multiple R-squared: 0.8865, Adjusted R-squared: 0.8541 ## F-statistic: 27.34 on 2 and 7 DF, p-value: 0.0004923 Interpretazione del modello ridotto: Intercetta (β 0 ): Valore medio per la categoria di riferimento (Femmine, dove dummy=0). Coefficiente Dummy (β dummy ): La differenza costante tra Maschi e Femmine. Years_Service (β 1 ): L’effetto degli anni di…
18/06/26, 16:14 exsercitazione 7 bestlam_ridge <- cv.ridge$lambda.min cat("Miglior lambda (min):", bestlam_ridge) ## Miglior lambda (min): 0.001 coefficienti ridge coef.ridge <- predict(ridge.mod, s = bestlam_ridge, type = 'coefficients') coef.ridge ## 8 x 1 sparse Matrix of class "dgCMatrix" ## s=0.001 ## (Intercept) -17.170940454 ## cylinders -0.480011244 ## displacement 0.019518208 ## horsepower -0.017196655 ## weight -0.006450341 ## acceleration 0.078067459 ## year 0.750125836 ## origin 1.423574049 lasso regression file:///C:/Users/aless/OneDrive/Desktop/BDAAEsercitazioni-20260415/Esercitazione 7/exsercitazione-7.html 25/28
18/06/26, 16:16 exsercitazione 9 Scelta: Scegliamo il valore di mtry che minimizza l’errore OOB (solitamente intorno a √– p). performance finale # Random Forest finale con mtry ottimale (es. 2) rf_final = randomForest(Survived ~ ., data=data_train, mtry=2, ntree=1000, importance=TRUE) pred_rf = predict(rf_final, newdata=data_test) misclass_rf = table(pred_rf, data_test$Survived) acc_rf = sum(diag(misclass_rf)) / sum(misclass_rf) cat("Accuratezza Random Forest sul Test Set:", acc_rf) ## Accuratezza Random Forest sul Test Set: 0.8084112 file:///C:/Users/aless/OneDrive/Desktop/BDAAEsercitazioni-20260415/Esercitazione 9/exseercitazione-9.html 29/29
First page of the document.