Se aseguran de que las librerías necesarias (tidyverse, ThesiStats, readxl, openxlsx) están instaladas y cargadas para su uso posterior en el análisis.
# Asegúrate de que todos los paquetes necesarios están instalados y cargados
library(tidyverse)
library(ThesiStats)
library(readxl)
library(openxlsx)
Se carga un archivo de Excel llamado “Data_toy.xlsx” en un data frame llamado df utilizando la función read_excel de la librería readxl.
df <- read_excel("Data_toy.xlsx")
Se renombra ciertas variables del data frame para mayor claridad y se elimina la variable Acepta_Participar del conjunto de datos.
df_new <- df %>%
rename(
Acepta_Participar = Aceptación,
Reside_Lima = `¿Reside en Lima?`,
Tiempo_Baila_Folklorica = `Tiempo en el que baila musica folklórica`,
Tiempo_Estudio = `¿Cuánto tiempo le dedica a los estudios?`
) %>%
select(-Acepta_Participar)
Se utiliza la función rename_items2 para renombrar ítems específicos en el data frame df_new. Los ítems están agrupados con prefijos SS y TP y los cambios se aplican desde el primer ítem hasta el último especificado.
df_new_renombrado <-rename_items2(df_new,
prefix1 = "SS",
prefix2 = "TP",
inicio = "1. Siento que mi vida vale la pena",
final = "5. No encuentro significado en las activdades realizadas" ,
n_items1 = 5,
n_items2 = 5)
Se convierten las expresiones cualitativas a valores numéricos en el data frame df_new_renombrado utilizando la función remplace_alternative_response.
column_mappings <- list(
list(c("SS1", "SS5"),
"1. Totalmente desacuerdo, 2. Desacuerdo, 3. Ni en acuerdo ni en desacuerdo, 4. Acuerdo, 5. Totalmente de acuerdo"),
list(c("TP1", "T5"),
"0. Nunca, 1. Rara vez, 2. A veces, 3. Casi siempre, 4. Siempre")
)
df_new_renombrado <- remplace_alternative_response(df_new_renombrado, column_mappings)
Se seleccionan columnas específicas del data frame df_new_renombrado y se almacenan sus nombres en columnas. Luego, se calculan porcentajes para estas columnas con la función calcular_porcentajes. Se muestran los resultados para las variables Sexo, Ocupación, Reside_Lima, y Tiempo_Baila_Folklorica. Finalmente, se utiliza edad_stat para obtener estadísticas de la variable Edad.
columnas <- df_new_renombrado %>% select(Sexo:Tiempo_Estudio, Edad) %>% colnames()
resultados_lista <- calcular_porcentajes(df_new_renombrado, columnas)
resultados_lista$Sexo
## # A tibble: 2 × 3
## Sexo n Porcentaje
## <chr> <int> <dbl>
## 1 Hombre 47 47
## 2 Mujer 53 53
resultados_lista$Ocupación
## # A tibble: 9 × 3
## Ocupación n Porcentaje
## <chr> <int> <dbl>
## 1 Administrador 13 13
## 2 Asistente contable 8 8
## 3 Comunicadora integral 8 8
## 4 Docente 9 9
## 5 Estudiante 15 15
## 6 Ingeniera Industrial 9 9
## 7 Médico 16 16
## 8 Músico 12 12
## 9 Prefiero no decirlo 10 10
resultados_lista$Reside_Lima
## # A tibble: 2 × 3
## Reside_Lima n Porcentaje
## <chr> <int> <dbl>
## 1 No 56 56
## 2 Sí 44 44
resultados_lista$Tiempo_Baila_Folklorica
## # A tibble: 4 × 3
## Tiempo_Baila_Folklorica n Porcentaje
## <chr> <int> <dbl>
## 1 1 - 2 años 25 25
## 2 2 - 3 años 20 20
## 3 Menos de 1 año 26 26
## 4 Más de 5 años 29 29
ThesiStats::edad_stat(df_new_renombrado, Edad)
## # A tibble: 1 × 4
## Media DesviacionEstandar Minimo Maximo
## <dbl> <dbl> <dbl> <dbl>
## 1 39.3 13.5 18 61
Se lee el archivo de texto “Texto.txt” y se genera código a partir de este utilizando la función generate_code, aplicándolo al data frame df_new_renombrado. Luego, se añaden dos nuevas variables (Satisfacción y Ánimo deprimido) calculadas como la suma de ciertos ítems (SS1 a SS5 y TP1 a TP5 respectivamente) para cada fila del data frame.
texto <- readLines("Texto.txt", encoding = "UTF-8")
code <- generate_code(texto, "df_new_renombrado")
cat(code)
## df_new_renombrado %>%
## rowwise() %>%
## mutate(Satisfacción = sum(c_across(c(SS1,SS2,SS3,SS4,SS5))),
## `Ánimo deprimido` = sum(c_across(c(TP1,TP2,TP3,TP4,TP5)))) %>%
## ungroup()
df_new_renombrado <- df_new_renombrado %>%
rowwise() %>%
mutate(Satisfacción = sum(c_across(c(SS1,SS2,SS3,SS4,SS5))),
`Ánimo deprimido` = sum(c_across(c(TP1,TP2,TP3,TP4,TP5)))) %>%
ungroup()
Se realiza una prueba de normalidad de Shapiro-Wilk para las variables Satisfacción y Ánimo deprimido en el data frame df_new_renombrado. Los resultados se guardan en un archivo Excel llamado “Apendice A.xlsx”.
result <- normality_test_SW(df_new_renombrado, c(Satisfacción:`Ánimo deprimido`))
result
## # A tibble: 2 × 4
## Variables `Shapiro-Wilk` p.value Normality
## <fct> <dbl> <chr> <chr>
## 1 Satisfacción 0.982 0.1930009 Normal
## 2 Ánimo deprimido 0.968 0.01689987 No-normal
openxlsx::write.xlsx(result, file = "Apendice A.xlsx", overwrite = T)
Se seleccionan las columnas Satisfacción y Ánimo deprimido del data frame df_new_renombrado. Luego, se crea un gráfico de boxplot para estas variables usando la función grafico_boxplots. Finalmente, el gráfico se guarda en alta calidad con el nombre “Apendice B.jpg”.s
columnas = df_new_renombrado %>% select(Satisfacción:`Ánimo deprimido`) %>% names()
p1 <- grafico_boxplots(df_new_renombrado, columnas)
p1
#guardar en alta calidad
ggsave(filename = "Apendice B.jpg", plot = p1,
height = 5, width = 8.5, dpi = 600)
Se seleccionan las columnas Satisfacción y Ánimo deprimido del data frame df_new_renombrado. Luego, se crea un gráfico de normalidad multivariante para estas variables usando la función Multivariate_plot, especificando los límites de los ejes. Finalmente, el gráfico se guarda en alta calidad con el nombre “Apendice C.jpg”.
p2 <- Multivariate_plot(df_new_renombrado %>% select(Satisfacción:`Ánimo deprimido`), xmin=6, xmax=9, ymin=0, ymax=2.5)
p2
#guardar en alta calidad
ggsave(filename = "Apendice C.jpg", plot = p2,
height = 5, width = 8.5, dpi = 600)
Primero, se calculan estadísticas descriptivas para las variables Satisfacción y Ánimo deprimido utilizando la función calculate_descriptives. Segundo, sSe extraen ítems del texto previamente leído y se calcula la fiabilidad (omega) para estos ítems con la función calcula_omega_all. Tercero, se crea una tabla combinando los descriptivos y los resultados de fiabilidad usando inner_join. Finalmente, se guarda esta tabla en un archivo Excel llamado “Tabla 1.xlsx” (la línea está comentada para no sobrescribir el archivo).
# Descriptivos
result1 <- calculate_descriptives(df_new_renombrado, "Satisfacción", "Ánimo deprimido")
# Fiabilidad
extracted <- extract_items(texto)
resultado_fiabilidad <- calcula_omega_all(extracted, df_new_renombrado)
print(resultado_fiabilidad)
## Variables Omega
## 1 Satisfacción 0.1908253
## 2 Ánimo deprimido 0.2951101
# Tabla 1
Tabla1 <- inner_join(result1, resultado_fiabilidad, by = "Variables")
Tabla1
## Variables Media DE Min. Max. g1 g2 % Omega
## 1 Satisfacción 14.98 3.18 7 22 -0.11 -0.45 68.09 0.1908253
## 2 Ánimo deprimido 9.85 3.47 2 19 0.01 -0.80 51.84 0.2951101
# Guardar la información
# openxlsx::write.xlsx(Tabla1, file = "Tabla 1.xlsx", overwrite = F)
Se calculan las correlaciones entre Satisfacción y Ánimo deprimido usando el método de Pearson, con opción de winsorize activada para tratar valores atípicos. Luego, la tabla de correlaciones se guarda en un archivo Excel llamado “Tabla 2.xlsx” (la línea está comentada para no sobrescribir el archivo).
Tabla2 <- calcular_correlaciones(df_new_renombrado,
"Satisfacción",
"Ánimo deprimido",
method = "pearson",
winsorize = T)
Tabla2
## 1 2
## 1. Satisfacción - <NA>
## 2. Ánimo deprimido 0.07 -
# Guardar información en un Excel
# openxlsx::write.xlsx(Tabla2, file = "Tabla 2.xlsx", overwrite = T, rowNames = F)
Se calcula una tabla comparativa para las variables Satisfacción y Ánimo deprimido en función de la variable Sexo, utilizando la función Calcule_Comparative con opción robusta activada. Luego, la tabla comparativa se guarda en un archivo Excel llamado “Tabla 3.xlsx” (la línea está comentada para no sobrescribir el archivo).
Tabla3 <- Calcule_Comparative(df_new_renombrado, columnas, group_var = "Sexo", Robust = T)
Tabla3
## # A tibble: 2 × 8
## Variables_interes `Hombre(SD1)` `Mujer(SD2)` t gl p d_cohen
## <fct> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
## 1 Satisfacción 14.98 (3) 14.98 (3.37) -0.00378 98.0 0.997 0.0112
## 2 Ánimo deprimido 10.3 (3.36) 9.45 (3.55) 1.22 97.6 0.225 0.268
## # ℹ 1 more variable: Interpretacion <chr>
# openxlsx::write.xlsx(Tabla3, file = "Tabla 3.xlsx", overwrite = T, rowNames = F)
Ventura-León, J. (2024). ThesiStats [Software]. GitHub. https://github.com/jventural/ThesiStats
Mair, P., & Wilcox, R. (2020). Robust statistical methods in R using the WRS2 package. Behavior Research Methods, 52. https://doi.org/10.3758/s13428-019-01246-w
Jorgensen, T. D., Pornprasertmanit, S., Schoemann, A. M., & Rosseel, Y. (2022). semTools: Useful tools for structural equation modeling (R package version 0.5-6). https://CRAN.R-project.org/package=semTools
Rosseel, Y. (2012). lavaan: An R package for structural equation modeling. Journal of Statistical Software, 48(2), 1-36. https://doi.org/10.18637/jss.v048.i02
Revelle, W. (2024). psych: Procedures for psychological, psychometric, and personality research (R package version 2.4.3). Northwestern University. https://CRAN.R-project.org/package=psych
Wickham, H., & Pedersen, T. L. (2024). gtable: Arrange ‘grobs’ in tables (R package version 0.3.5). https://CRAN.R-project.org/package=gtable
Auguie, B. (2017). gridExtra: Miscellaneous functions for “grid” graphics (R package version 2.3). https://CRAN.R-project.org/package=gridExtra
Korkmaz, S., Goksuluk, D., & Zararsiz, G. (2014). MVN: An R package for assessing multivariate normality. The R Journal, 6(2), 151-162. https://journal.r-project.org/archive/2014-2/korkmaz-goksuluk-zararsiz.pdf
Wickham, H. (2007). Reshaping data with the reshape package. Journal of Statistical Software, 21(12), 1-20. http://www.jstatsoft.org/v21/i12/
Robinson, D., Hayes, A., & Couch, S. (2024). broom: Convert statistical objects into tidy tibbles (R package version 1.0.6). https://CRAN.R-project.org/package=broom
Schauberger, P., & Walker, A. (2023). openxlsx: Read, write and edit xlsx files (R package version 4.2.5.2). https://CRAN.R-project.org/package=openxlsx
Wickham, H., & Bryan, J. (2023). readxl: Read excel files (R package version 1.4.3). https://CRAN.R-project.org/package=readxl
Ventura, J. (2024). ThesiStats: Thesis analysis tools for statistical computing (R package version 1.0.0, commit fadbbdbb3f477610e148fa74ea12ceacadb02494). https://github.com/jventural/ThesiStats
Grolemund, G., & Wickham, H. (2011). Dates and times made easy with lubridate. Journal of Statistical Software, 40(3), 1-25. https://www.jstatsoft.org/v40/i03/
Wickham, H. (2023). forcats: Tools for working with categorical variables (factors) (R package version 1.0.0). https://CRAN.R-project.org/package=forcats
Wickham, H. (2023). stringr: Simple, consistent wrappers for common string operations (R package version 1.5.1). https://CRAN.R-project.org/package=stringr
Wickham, H., François, R., Henry, L., Müller, K., & Vaughan, D. (2023). dplyr: A grammar of data manipulation (R package version 1.1.4). https://CRAN.R-project.org/package=dplyr
Wickham, H., & Henry, L. (2023). purrr: Functional programming tools (R package version 1.0.2). https://CRAN.R-project.org/package=purrr
Wickham, H., Hester, J., & Bryan, J. (2024). readr: Read rectangular text data (R package version 2.1.5). https://CRAN.R-project.org/package=readr
Wickham, H., Vaughan, D., & Girlich, M. (2024). tidyr: Tidy messy data (R package version 1.3.1). https://CRAN.R-project.org/package=tidyr
Müller, K., & Wickham, H. (2023). tibble: Simple data frames (R package version 3.2.1). https://CRAN.R-project.org/package=tibble
Wickham, H. (2016). ggplot2: Elegant graphics for data analysis. Springer-Verlag New York. https://ggplot2.tidyverse.org
Wickham, H., Averick, M., Bryan, J., Chang, W., McGowan, L. D., François, R., Grolemund, G., Hayes, A., Henry, L., Hester, J., Kuhn, M., Pedersen, T. L., Miller, E., Bache, S. M., Müller, K., Ooms, J., Robinson, D., Seidel, D. P., Spinu, V., Takahashi, K., Vaughan, D., Wilke, C., Woo, K., & Yutani, H. (2019). Welcome to the tidyverse. Journal of Open Source Software, 4(43), 1686. https://doi.org/10.21105/joss.01686