










Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Prepara tus exámenes
Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Prepara tus exámenes con los documentos que comparten otros estudiantes como tú en Docsity
Encuentra los documentos específicos para los exámenes de tu universidad
Estudia con lecciones y exámenes resueltos basados en los programas académicos de las mejores universidades
Responde a preguntas de exámenes reales y pon a prueba tu preparación
Consigue puntos base para descargar
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Comunidad
Pide ayuda a la comunidad y resuelve tus dudas de estudio
Ebooks gratuitos
Descarga nuestras guías gratuitas sobre técnicas de estudio, métodos para controlar la ansiedad y consejos para la tesis preparadas por los tutores de Docsity
comandos para Rstudio, stata y excel
Tipo: Apuntes
1 / 18
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!











EXCEL → .xlsx
R. i RSTUDIO → .cvs (format text, cada línia conté un cas d’un conjunt de dades i els valors
de cada variable separats per comes)
STATA → .dta/.do
+INFO → help.start()
AJUDA →? …………………………………………………. ?C
ASSIGNAR UN VALOR → <- ……………………………………. x<-5+7 (x=12)
VECTOR → c()
MULTIPLICACIÓ “*”// SUMA “+”// RESTA “-”// DIVISIÓ”/”// AL QUADRAT”^”//
ARREL QUADRADA “sqrt()”// VALOR ABSOLUT “abs()”
TAULA DE FREQÜÈNCIES →(obrir package fdth) print(fdt(arxiu$dades))
TAU DE FREQ → statistics -> summaries, tables and tests -> tables -> one -> way tables CALCULADORA → di
1- Importar fitxer
2- Comprovar si s’han llegit les dades correctament amb → head(nom fitxer)
3- Extreure una variable (mpgCity) del nostre conjunt de dades (cars)
conjunt_de_dades$variable → cars$mpgCity
4- Emmagatzemar com my(variable)
myMPG<-cars$mpgCity
MITJANA → mean(arxiu$variable) ………….. ex: mean(myMPG)
MEDIANA → median(arxiu$variable). ……… ex: median(myMPG)
MODA → table(arxiu$variable) ……………… ex: table(myMPG)
RANG DE VARIACIÓ → range(arxiu$variable)..... ex: range(cars$price)
VARIANÇA → var(arxiu$variable) …………….. ex: var(cars$price)
DESVIACIÓ ESTÀNDAR → sd(arxiu$variable) …. ex: sd(cars$price)
COEF. DE VARIACIÓ → sd(arxiu$variable)/mean(arxiu$variable)
5 NÚMEROS RESUM→ fivenum(arxiu$variable)..................... ex: fivenum(cars$price)
DIAGRAMA DE CAIXES→ summary(arxiu$variable) ……….... ex: summary(myMPG)
CONJUNT RESUM + COMPLET → describe(arxiu$variable)..... ex: describe(myMPG)
MEAN mitjana MAX màxim
SD variació estàndar RANGE recorregut
MEDIAN mediana SKEW coef. assimetria
MIN mínim KURTOSIS curtosis
DIAGRAMA DE CAIXES → boxplot(arxiu$variable) ……… boxplot(Assistencia$estudiants)
HISTOGRAMA → hist(arxiu$variable) …………………… hist(Assistencia$estudiants)
DIAGRAMA TRONCS I FULLES → stem(arxiu$variable)...... stem(Assistencia$estudiants)
HISTOGRAMA → hist (nomvariable).................................................. hist Dies
DIAGRAMA TRONCS I FULLES → stem (nomvariable) ………........... stem Dies
per desdoblament en 2 → stem (nomvariable), width (5)......... stem Dies, width(5) Els troncs que contenen els dígits 0-4 s'indiquen amb "*" i els que contenen 5-9 s'indiquen amb "."
per desdoblament en 5 → stem (nomvariable), width (2)......... stem Dies, width(2) Troncs que contenen zeros i uns s'indiquen amb "*" " " " dosos " tres " " "t" " " " quatres " cincs " " "f" " " " sisos " sets " " "s" " " " vuits " nous " " "." per canviar arrodoniment → stem (nomvariable), round(0.1).... stem Dies, round(0.1)
DIAGRAMA DE CAIXES → graph box (nomvariable) …………………. graph box Dies
TAU FREQ. ABS → table(arxiu$variable) …………………. table(barris$Barri)
TAU FREQ. REL → prop.table(table(arxiu$variable)) …….. prop.table(table(barris$Barri))
en % → 100prop.table(table(arxiu$variable)) …. 100prop.table(table(barris$Barri)
GRÀFICA DE SECTORS → variable.freq<-table(arxiu$variable) (ENTER) pie(variable.freq)
………... barri.freq<-table(barris$Barri) (ENTER) pie(barri.freq)
DIAGRAMA DE BARRES → variable.freq<-table(arxiu$variable) (ENTER) barplot(var.freq)
……. barri.freq <- table(barris$Barri) (ENTER) barplot(barri.freq)
GRÀFICA DE SECTOR AMB VAR. REL → var.freq<-prop.table(table(arxiu$var) pie(var.freq)
DIAGR. DE BARRES AMB VAR. REL → var.freq<-prop.table(table(arxiu$var) barplot(var.freq)
TAU FREQÜÈNCIES → tabulate (variable) …………………….. tabulate Barri
GRÀFICA DE SECTORS → graph pie, over (variable) ………….. graph pie, over (Barri)
DIAGRAMA DE BARRES → graph bar, over (variable) ………... graph bar, over (Barri)
VEURE CASOS DEL MARC DE DADES → head(arxiu) ………… head(viatge)
RESUMS NUMÈRICS → describe(arxiu$variable) …………… describe(viatge$euros)
TRANSFORMACIÓ LINEAL A UNA VARIABLE X → nounom1<-(arxiu$variable-a)/b
NOU MARC DE DADES AMB VARIABLE TRANSF → nounom2<-data.frame(nounom1)
ARRODONIR (2 DECIM) → nounom2$nounom1<-round(nounom2$nounom1,2)
mitjana_lliures =(mitjana_euros - a)/b
mediana_lliures = (mediana_euros -a)/b
desv_estand_lliures = desv_estand_euros/b
(les mesures de dispersió no es veuen afectades pel canvi d'origen), i per últim les mesures de
forma no canvien quan s'apliquen transformacions lineals.
TRANSFORMACIÓ LOGARÍTMICA → log(arxiu$variable)
TRANSFORMACIÓ DADES LINEALS → gen ……… gen pounds = (variable-a)/b
VEURE RESULTATS → summarize variable, detail ………. summarize euros, detail
summarize pounds, detail
TRANSFORMACIÓ LOGARÍTMICA → gen log_variable=log(variable)
DETERMINAR QUIN DIRECTORY ESTÀ USANT LA SESSIÓ → getwd()
FER LLISTA DE TOTS ELS OBJECTES AL MEU ESPAI LOCAL → ls()
FER LLISTA DE TOTS ELS FITXERS AL MEU DIRECTORY → list.files() o dir()
DETERMINAR ELS ARGUMENTS DE list.files() → args(list.files)
CREAR UN DIRECTORY AL DIRECTORY DE TREBALL ACTUAL → dir.create(“testdir”)
ESTABLIR EL MEU DIRECTORI DE TREBALL A testdir → setwd("testdir")
CREAR UN FITXER AL MEU DIRECTORY → file.create(“nom”)
MIRAR SI EXISTEIX FITXER → file.exists(“nomfitxer”)
INFO DEL FITXER → file.info(“nomfitxer”)
CANVIAR NOM FITXER → file.rename("nomfitxer", "nounomfitxer")
FER CÒPIA FITXER → file.copy("nomfitxer", "nomcopiafitxer")
MOSTRAR CAMÍ RELATIU AL FITXER → file.path("nomcopiafitxer")
CONSTRUIR CAMINS A FITXERS I DIRECTORIS INDEPENDENTMENT DEL SISTEMA OPERATIU
ON EL MEU CODI DE R ESTÀ EXECUTANT → file.path("folder1", "folder2")
COEFICIENT DE CORRELACIÓ → =coef.de.correl(matriu1;matriu2)
Abans de iniciar l’anàlisi de relacions entre variables → realitzar anàlisi detallat amb boxplot per cada variable.
DIAGRAMA DE DISPERSIÓ → plot(arxiu) ……………………………... plot(rendiment) CORRELACIÓ → cor(X,Y) ……………………………………………... cor(parcial,final) CONSTANT I PENDENT LÍNIA DE REGRESSIÓ → lm(Y~X)………………. lm(final~parcial) LÍNIA DE REGRESSIÓ → abline(lm(Y~X)) ……………………… abline(lm(final~parcial))
pendent= a sota columna Coef. DEMANAR PREDICCIÓ → adjust X = valor de la una x CALCULAR RESIDUS → predict nomarxiu, residuals ________ histogram nomarxiu DIAGRAMA DE RESIDUS → scatter nomarxiu X, yline(0) title (“títol”) yline(0) = línia horitzontal a y= IDENTIFICAR PUNTS AMB NÚMERO DE CAS → scatter Y X, mlabel(nomvariableobservacions) title (“títol”) ELIMINAR CASOS→ drop if nomvariableobservacions==
MODEL LOG-LOG → gen lY=log(Y) gen lX=log(X) DIAGRAMA DE DISPERSIÓ AMB MODEL LOG-LOG → scatter lY lX REVERTIR TRANSFORMACIÓ → di exp (constant + correlació*log(x))
PACKAGES —> nlme + data.table + ggplot
1- FER DIAGRAMA DE DISPERSIÓ plot(nomarxiu$variableY~nomarxiu$variableX) 2- LÍNIA DE REGRESSIÓ abline(lm(nomarxiu$variableY~nomarxiu$variableX)) 3- AFEGIR VARIABLE CATEGÒRICA ggplot(nomarxiu,aes(y=nomvariableY,x=nomvariableX,colour=nomvariablecategòrica,shape =nomvariablecategòrica))+geom_point() 4- LÍNIES DE REGRESSIÓ X CADA CATEGORIA ggplot(nomarxiu,aes(y=nomvariableY,x=nomvariableX,colour=nomvariablecategòrica,shape =nomvariablecategòrica))+geom_point()+geom_smooth(method=”lm”,fill=NA) 5- COEF CORRELACIÓ X CADA CATEGORIA dt<-data.table(nomarxiu) (enter) dt[,list(cor(y,x)),by=nomvariablecategòrica] 6- COEF REGRESSIÓ LINEAL X CADA CATEGORIA lmList(Y~X|nomvariablecategòrica,data=nomarxiu)
PACKAGES → psych, lattice, gplots
describeBy(nomarxiu$variablenumèrica,nomarxiu$variablecategòrica)
boxplot(nomarxiu$variablenumèrica~nomarxiu$variablecategòrica,data=nomarxiu,xlab=”N OMVARCATEGÒRICA”,ylab=”NOMVARNUMÈRICA”)
histogram(~nomvariablenumèrica|factor(nomvariablecategòrica),data=nomarxiu,xlab=”no mvariablenumèrica”)
plotmeans(nomarxiu$variablenumèrica~nomarxiu$variablecategòrica,data=nomarxiu)
Per a variables categòriques ordinals, posar 1. / 2. / 3. / … devant de cada categòrica
OBTENIR RESUMS DE VARIABLE NUMÈRICA PER A CADA CATEGÒRICA → bysort nomvariablecategòrica: summarize nomvariablenumèrica OBTENIR RESUMS MÉS COMPLERTS → bysort nomvariablecategòrica: summarize nomvariablenumèrica, detail DIAGRAMA DE CAIXES → graph box nomvariablenumèrica, over(nomvariablecategòrica) HISTOGRAMA → histogram nomvariablenumèrica, by(nomvariablecategòrica) TRONC I FULLES → bysort nomvariablecategòrica: stem nomvariablenumèrica DIAGRAMA DE BARRES DE RESUM NUMÈRIC → graph bar nomvariablenumèrica, over(nomvariablecategòrica) // graph bar (sd/median/iqr) nomvariablenumèrica, over(nomvariablecategòrica)
OBTENIR DISTRIBUCIÓ CONJUNTA → tabulate variablefila variablecolumna [fw=Freq] FREQ. RELATIVES DISTRIBUCIO CONJUNTA I MARGINALS → tabulate variablefila variablecolumna, cell DISTRIBUCIONS CONDICIONALS VARIABLE FILA CONDICIONADA COLUMNA → tabulate variablefila variablecolumna, col DISTRIBUCIÓ CONDICIONALS VARIABLE COLUMNA CONDICIONADA A FILA → tabulate variablefila variablecolumna, row OBTENIR DIAGRAMA DE BARRES → graph bar(sum) Freq, over(variablefila) over(variablecolumna) asyvars percentage stack
seq(num,num) …………… seq(1:20)
ENTRAR UN SEQÜÈNCIA DE NÚMEROS AMB INCREMENT → seq(num,num,by=0.5) ENTRAR UN SEQÜÈNCIA DE NÚMEROS AMB X NOMBRES→ seq(num,num,length=30) NOU VECTOR AMB = length → 1:length(my_seq) // seq(along.with = my_seq) CREACIÓ DE SEQÜÈNCIES DE NÚMEROS → exemple vector amb 40 zeros ... rep(0,times=40) rep(c(0, 1, 2), each = 10) rep(c(0, 1,2),times=10)
VECTORS ATÒMICS ( 1 tipus de dades)
L'argument «collapse» a la funció paste() -> quan unim els elements del vector de caràcters my_char, volem separar-los amb un espai paste(my_char,collapse=" ")
LLISTES (múltiples tipus de dades)
MATRIU → només pot contenir una única classe de dades MARCS DE DADES → poden contenir moltes classes diferents de dades
CREEM VECTOR → my_vector<-1:20 I OBRIM → my_vector SABER LONGITUD OBJECTE → length(my_vector) OBTENIR ATRIBUT PER A UN OBJECTE → dim(my_vector)<-c(4,5) (4 files i 5 columnes) VEURE ATRIBUTS → attributes(my_vector) CONFIRMAR QUE ÉS UNA MATRIU → class(my_vector) CREAR UNA MATRIU → my_matrix2<-matrix(1:20,nrow=4,ncol=5,byrow=FALSE,dimnames=NULL) MIRAR SI DOS OBJECTES SÓN IDÈNTICS → identical(objecte1,objecte2) POSAR VARIABLE NOM INDIVIDUS X FILES → patients<-c(“NOM1”, NOM2”) COMBINAR COLUMNES → my_data<-data.frame(patients,my_matrix) POSAR NOM VARIABLE X COLUMNES → cnames<-c("pacient","edat","pes","pa","rating","test") i colnames(my_data)<-cnames
SÈRIE TEMPORAL → ts(nomarxiu$variable, start=c(any,trimestre), freqüència=nºtrimestres) …………. gelats.ts<-ts(gelats$vendes, start=c(2012,1),frequency=4) REPRESENTACIÓ GRÀFICA → plot.ts(nomarxiu$variable, start=c(any,trimestre), freqüència=nºtrimestres) DESCOMPOSAR SÈRIE → decomp.ts <-decompose(gelats.ts,type="additive/multiplicative") VEURE VALORS TENDÈNCIA → decomp.ts$trend GRÀFICA TENDÈNCIA → ts.plot(gelats.ts,decomp.ts$trend) // autoplot(gelats.ts,series="Vendes")+autolayer(decomp.ts$trend, series= "TendènciaMA4")+labs(x="Trimestre", y="Vendes de gelat")+ggtitle("Vendes de gelat amb tendència") VEURE VALORS ESTACIONALITAT → decomp.ts$seasonal + decomp.ts$figure
generate temps = tq(2012q1) + _n- format %tq temps tsset temps
ÍNDEX DE GINI → gini(nomarxiu$nomvariable,coefnorm=TRUE) CURVA DE LORENZ → lorenz(valoríndexgini)
PUNTS MIGS INTÈRVALS → x <- c(5000,55000,550000,6000000) ENTRAR FREQÜÈNCIES → w <- c(70.1, 21.3,7.9,0.7) ÍNDEX DE GINI → gini(x,weighting=w) CURVA DE LORENZ → lorenz(x,weighting=w)
ÍNDEX DE HERFINDAHL → herf(nomvariable)
q.A<- c(100,125,150) p.A<- c(10000,12500,13000)
ENTRAR VECTORS EN UN MARC DE DADES → Dades<-data.frame(q.A,p.A,q.B,p.C,...) COMPLETAR DADES AMB ELS ANYS → rownames(Dades) <- c(1997,1998,1999) MIRAR TAULA → Dades
pL <- priceIndex( c( "p.A", "p.B","p.C" ),c( "q.A", "q.B", "q.C" ), 1, Dades)* (on 1=any base) enter pL
GRÀFICA DE SÈRIE TEMPORAL → plot.ts(pL)
AMB PONDERACIONS → apply(Dades3, 1,function(x) weighted.mean(x[1:3],x[4:6]))