Librerias R

library(reticulate)
#py_install("tabulate")
#py_install('Jinja2')
#py_install(ipywidgets)
library(tidyverse)
library(flextable)
#library(grid)
library(scales)
#library(gridExtra)
library(patchwork)
library(RColorBrewer)
library(tm)
library(wordcloud)
set_flextable_defaults(font.family = "Calibri",
                       font.size = 10,
                       border.color = "dodgerblue3",
                       background.color = "aliceblue")

Lectura datos encuesta R

# DATOS 2022

# Datos de base
prim <- read.csv(unzip("Cuestionario alumnado 5º-6º.csv.zip"),
                   header = TRUE, 
                   encoding = "UTF-8") 
prim <- prim[, -28] # eliminada la columna'X' generada per una manipulació del drive

#Cuadro específicamente creado en excel y guardado en csv
variablesPrim <- read.csv("nombres_varPrim.csv",
                             header = TRUE, sep=";") # Ha habido que eliminar previamente los blank spaces

variablesPrim$var <- trimws(variablesPrim$var, which = c('both'))
variablesPrim$var <- make.names(variablesPrim$var)
colnames(prim) <- variablesPrim$var

prim <- subset(prim,!duplicated(prim[,2:length(prim)])) # No hay duplicaciones

prim['año'] <- '2022'

#prim <- prim[-c(1:4), ] # Eliminación registros de prueba

textopiePrim <- "Fuente: elaboración propia a partir de las respuestas al CUESTIONARIO DE EVALUACIÓN Y LÍNEA DE BASE PARA ALUMNADO DE PRIMARIA"
dim(prim)
## [1]  5 28

Librerias Python


import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

Lectura datos encuesta Python


pydat= pd.read_csv('Cuestionario alumnado 5º-6º.csv.zip', encoding='utf-8')

#Cuadro específicamente creado en excel y guardado en csv
varPrim= pd.read_csv("nombres_varPrim.csv",sep=";")
varPrim.columns.str.strip()
## Index(['var'], dtype='object')
pydat.columns = varPrim['var'] # Canvi noms de les columnes

#Eliminar duplicats
consider = [x for x in pydat.columns if x != "marca"]
pydat= pydat.drop_duplicates(subset=consider).reset_index(drop='last')

pydat['año'] = '2022'

#pydat.drop(pydat.index[:4]) # Eliminación registros de prueba

textopiePyPri = "Fuente: elaboración propia a partir de las respuestas al CUESTIONARIO DE EVALUACIÓN Y LÍNEA DE BASE PARA ALUMNADO DE PRIMARIA"

pydat.shape
## (5, 28)

Lectura datos encuesta 2020 R

# DATOS LINEA DE BASE

library(readxl)

prim2020 <- read.csv("Formulario Actividades APSC Primaria.csv",
         encoding = "UTF-8")

VariablesPrim2020 <- read_xlsx("VariablesPrimaria.xlsx",
                             sheet = "Hoja1",
                             range = "Hoja1!A1:B14",
                             col_names = FALSE)
colnames(prim2020) <- VariablesPrim2020$...2

prim2020 <- prim2020 %>% mutate(año='2020')
dim(prim2020)
## [1] 159  15

Lectura datos encuesta 2020 Python


# DATOS LINEA DE BASE

pyd20 = pd.read_csv("Formulario Actividades APSC Primaria.csv", encoding = "utf-8")

varpy20 = pd.read_csv("VariablesPrimaria_csv.csv",encoding="latin-1",delimiter= ';',header=None)

pyd20.columns = varpy20[1] # Canvi noms de les columnes


pyd20['año'] = '2020'
pyd20.shape
## (159, 15)

Introducción al análisis

Los datos que han sido tratados han surgido de la muestra voluntaria, que respondió al “CUESTIONARIO DE EVALUACIÓN Y LÍNEA DE BASE PARA ALUMNADO DE PRIMARIA” que se distribuyó online a profesores y profesoras, entre los días NA y NA. La muestra final es de 0 informantes, sin descartar ningún cuestionario, ya que no se encontraron errores.

Perfil de la persona encuestada

1. Centro educativo: (desplegable)

  • Colegio José Arnauda
  • Colegio Nuestra Señora de los Ángeles
  • Colegio Santa Teresa
  • Colegio El Armelar
  • IES Vicent Andrés Estellés
  • Centro Rural Agrupado Alt Carraixet


#TabCEducatPrim <- prim %>% filter(P1.centro!= '')

TabCEducatPrim <- prim |> 
  group_by(P1.centro) %>%
  summarise(n=n()) %>%
  mutate(Porcentaje= scales::percent(n/nrow(prim)))
    
TabCEducatPrim %>% 
  flextable() %>% 
    width(width = 2) %>% 
    set_header_labels(P1.centro = "Centro educativo",
                      n= "n",
                      Porcentaje= "Porcentaje") %>% 
    footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

1 Centro educativo python

#py_install('tabulate')
#py_install('Jinja2')
tabCentrPy =pydat.groupby('P1.centro').size().reset_index(name= 'Num')
tabCentrPy['Porcentaje'] = tabCentrPy['Num'] /len(pydat)
tabCentrPy.columns = ['centro','n','Porcentaje']
tabCentrPy.style.format({'Porcentaje': '{:.2%}'})\
    .hide_index()\
    .set_properties(**{'background-color': 'aliceblue','color':'black','border-color': 'black'})\
    .set_properties(subset=['n'], **{'width': '40px','text-align': 'center'})\
    .set_properties(subset=['centro'], **{'width': '300px'})\
    .set_properties(subset=['Porcentaje'], **{'width': '150px','text-align': 'center'})\
    .set_caption(textopiePyPri)\
    .set_table_styles(
   [{
       'selector': 'th',
       'props': [('background-color', 'aliceblue'),
        ('border-style', 'solid'),
        ('border-width', '2px'),
        ('border-color', 'blue')]
   },
       {"selector": "tbody td", "props": [("border", "1px solid grey")]},
       {'selector': 'caption', 'props': [('caption-side', 'bottom'),
       ("font-size", "75%")]}
  ])
Fuente: elaboración propia a partir de las respuestas al CUESTIONARIO DE EVALUACIÓN Y LÍNEA DE BASE PARA ALUMNADO DE PRIMARIA
centro n Porcentaje
Centro Rural Agrupado Alt Carraixet 1 20.00%
Colegio El Armelar 1 20.00%
Colegio José Arnauda 1 20.00%
Colegio Nuestra Señora de los Ángeles 2 40.00%


2. Te identificas como:

  • Niño
  • Niña
  • Prefiero no decirlo


TabGenPrim <- prim |> 
  group_by(P2.sexo) %>%
  summarise(n=n()) %>%
  mutate(Porcentaje= scales::percent(n/nrow(prim)))


TabGenPrim %>%  
    flextable() %>% 
    width(width = 2) %>% 
    set_header_labels(P2.sexo="Sexo", n= "n", Porcentaje="Porcentaje") %>% 
    footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

2. Sexo Python

tabSexPy = pydat.groupby('P2.sexo').size().reset_index(name= 'Num')
tabSexPy['Porcentaje'] = tabSexPy['Num'] /len(pydat)
tabSexPy.columns = ['sexo','n','Porcentaje']
tabSexPy.style.format({'Porcentaje': '{:.2%}'})\
    .hide_index()\
    .set_properties(**{'background-color': 'aliceblue','color':'black','border-color': 'black'})\
    .set_properties(subset=['n'], **{'width': '40px','text-align': 'center'})\
    .set_properties(subset=['sexo'], **{'width': '300px'})\
    .set_properties(subset=['Porcentaje'], **{'width': '150px','text-align': 'center'})\
    .set_caption(textopiePyPri)\
    .set_table_styles(
   [{
     'selector': 'table',
     'props': [('border-collapse', 'collapse;'),
     ('padding', '0px;')]},
     {
       'selector': 'th',
       'props': [('background-color', 'aliceblue'),
        ('border-style', 'solid'),
        ('border-width', '2px'),
        ('border-color', 'blue')]
   },
       {"selector": "tbody td", "props": [("border", "1px solid grey")]},
       {'selector': 'caption', 'props': [('caption-side', 'bottom'),
       ("font-size", "75%")]}
  ])
Fuente: elaboración propia a partir de las respuestas al CUESTIONARIO DE EVALUACIÓN Y LÍNEA DE BASE PARA ALUMNADO DE PRIMARIA
sexo n Porcentaje
Niña 2 40.00%
Niño 3 60.00%

3. Clase

  • 5 Primaria
  • 6 Primaria


prim %>% group_by(P3.clase) %>%
    summarise(n=n()) %>%
    mutate(Porcentaje= scales::percent(n/ nrow(prim))) %>% 
    flextable() %>% 
    width(width = 2) %>% 
    set_header_labels(P3.clase= "Clase", n="n", Porcentaje= "Porcentaje") %>% 
    footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

EVALUACIÓN

4. ¿Has realizado en algún curso anterior actividades sobre cómo podemos transformar nuestro mundo?

  • Sí, muchas
  • Algunas
  • Pocas
  • Ninguna que recuerde
pr04a <- prim |>  group_by(P4.actividades) %>%
    summarise(n=n(), Porcentaje=n/nrow(prim)) %>%
    ggplot(aes(x=P4.actividades,
               y=Porcentaje,
               fill=P4.actividades))+
    geom_bar(stat = "identity")+
    geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=2,size=5, colour="white")+
    scale_y_continuous(labels = scales::percent)+
    ggtitle('¿Has realizado en algún curso anterior actividades sobre cómo podemos \ntransformar nuestro mundo?')+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 12))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="none")+
    scale_fill_brewer(palette="Dark2")


# Segmentación por centros educativos
pr04b <- prim |>  group_by(P1.centro, P4.actividades) %>%
    summarise(n1=n()) %>% left_join(TabCEducatPrim[,c(1,2)]) %>% 
    mutate(Porcentaje=n1/n) %>% 
    ggplot(aes(P4.actividades,
               y=n1, 
               fill=P4.actividades))+
    geom_bar(stat = "identity")+
    facet_wrap(~P1.centro)+
    scale_y_continuous(breaks= pretty_breaks())+
    #scale_fill_discrete(name=NULL)+
    #guides(fill=guide_legend(title=NULL))+
    geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=2,size=5, colour= 'white')+
    ggtitle("Segmentación de las respuestas por centro educativo")+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 12))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="none") +
    theme(axis.text.x = element_blank())+
    scale_fill_brewer(palette="Dark2")

pr04a / pr04b +
   plot_annotation(title = 'Actividades sobre "transformación del mundo"',
                   caption = textopiePrim,
                   theme = theme(plot.title = element_text(size = 18, 
                                                           face = 'bold',
                                                           colour = 'dodgerblue3',
                                                           hjust = 0.5),
                                 plot.caption = element_text(hjust = 0)))

4. Versión Python



df1= pydat.groupby('P4.actividades').size()/len(pydat)        #.reset_index(name= 'Num')
#tabP4['Porcentaje'] = tabP4['Num'] /len(pydat)
df1 = df1.mul(100)
df1 = df1.rename('percent').reset_index()
df1.rename(columns = {'P4.actividades':'actividades'}, inplace=True)


sns.set_palette('Dark2')

g = sns.catplot(x='actividades',y='percent',kind='bar',
                data=df1, 
                order=df1.actividades.unique(),
                height=5, aspect=1.5).set(ylim=(0,100))
#g.ax.set_ylim(0,100)
plt.title('¿Has realizado en algún curso anterior actividades \nsobre cómo podemos transformar nuestro mundo?',
          weight= 'bold',fontsize=12,y=0.93)


for p in g.ax.patches:
    txt = str(p.get_height().round(2)) + '%'
    txt_x = p.get_x() 
    txt_y = p.get_height()
    g.ax.text(txt_x+0.3,txt_y-5,txt, color='white')





plt.xlabel(None)
plt.ylabel(None)

plt.show()


plt.figure(figsize=(10, 6)) 
df2= pydat.groupby('P1.centro')['P4.actividades'].value_counts(normalize=True)

df2 = df2.mul(100)
df2 = df2.rename('percent').reset_index()
df2.rename(columns = {'P4.actividades':'actividades'}, inplace=True)


sns.set_palette('Dark2')

g1 = sns.FacetGrid(df2, col='P1.centro', hue='actividades', col_wrap=2, height=3,aspect=1.5)\
    .set(ylim=(0,100))
g1.map(sns.barplot,'actividades', 'percent', order=df2.actividades.unique()).set_xticklabels([])\
    .set(xlabel=None)\
    .add_legend(loc=4)\
    .legend.set_title(None)

#sns.set(rc = {'figure.figsize':(10,5)})
#sns.set_palette('Dark2')

axes = g1.axes.flatten()
axes[0].set_title(axes[0].get_title()[12:],y=1)
axes[1].set_title(axes[1].get_title()[12:],y=1)
axes[2].set_title(axes[2].get_title()[12:],y=1)
axes[3].set_title(axes[3].get_title()[12:],y=1)


for ax in g1.axes:
    for p in ax.patches:
             ax.annotate("%.1f" % p.get_height()+'%', (p.get_x() + p.get_width() / 2., p.get_height()),
                 ha='center', va='center', fontsize=11, color='white', xytext=(0, -10),
                 textcoords='offset points')

g1.fig.suptitle('Segmentación de las respuestas por centro educativo',y=.95, weight= 'bold')           
          

5. Sobre qué temáticas habéis trabajado más, puntuando de 1 a 5 (1= hemos trabajado poco o nada; 5= hemos trabajado muchísimo):

Igualdad entre mujeres y hombres / El cuidado de la naturaleza / La diversidad / La paz La justicia / El consumo responsable / El trabajo en equipo / Los Derechos humanos / Los problemas de mi barrio y de mi ciudad / Los ODS (Objetivos de Desarrollo Sostenible

d <- prim

# Es crea un nou dataframe amb les 10 variables en una, per tal de poder fer facet_wrap que permet fer servir el mateix y-axis i comparar millor (patchwork no ho deixa fer en el cas del geom_histogram)

d<- pivot_longer(d, 6:15,'grp') |> 
    mutate(grp = case_when(
    grp== 'P5.1.igualdad'~ 'Igualdad mujeres y hombres',
    grp== 'P5.2.naturaleza'~ 'Cuidado de la naturaleza',
    grp== 'P5.3.diversidad'~ 'La diversidad',
    grp== 'P5.4.paz'~ 'La paz',
    grp== 'P5.5.justicia'~ 'La justicia',
    grp== 'P5.6.consumo.resp'~ 'Consumo responsable',
    grp== 'P5.7.equipo'~ 'El trabajo en equipo',
    grp== 'P5.8.ddhh'~ 'Derechos Humanos',
    grp== 'P5.9.probciudad.'~ 'Poblemas de mi ciudad y mi barrio',
    grp== 'P5.10.ods'~ 'Los ODS')) |> 
    mutate(grp=str_wrap(grp, width = 20))

# calcular a banda els avg per posar en map2
grpavg <- d |> group_by(grp) |> summarise(avg= mean(value))
# calcular a banda els noms per posar en map2
category_name <- list(grpavg[[1]])

pr5a<- ggplot(d, aes(x=value, fill=..x..)) +
  geom_histogram(aes( y = ..count..),bins = 5) +
  facet_wrap(~grp,ncol = 5)+
  ylab("")+
  xlab("")+
  theme_classic() +
  theme(plot.title = element_text(hjust=0.5, face = "bold", size = 10))+
  theme(axis.title.x = element_text(face = "bold", size = 13))+
  theme(axis.title.y = element_text(face = "bold", size = 13))+
  theme(legend.position="none")+
  map2(grpavg[[2]], category_name[[1]], # són els vectors .x i .y que van més avall
       ~geom_vline(data=filter(d, grp==.y),
                   aes(xintercept = .x),
                   linetype=2, colour="orange", size = 1))

pr5b <- prim |> summarise(across(.cols = c(P5.1.igualdad:P5.10.ods),mean)) |> 
  pivot_longer(cols = c(1:10),names_to = 'Temas', values_to = 'Punt.Media') |> 
  mutate(Temas = case_when(
    Temas== 'P5.1.igualdad'~ 'Igualdad mujeres y hombres',
    Temas== 'P5.2.naturaleza'~ 'Cuidado de la naturaleza',
    Temas== 'P5.3.diversidad'~ 'La diversidad',
    Temas== 'P5.4.paz'~ 'La paz',
    Temas== 'P5.5.justicia'~ 'La justicia',
    Temas== 'P5.6.consumo.resp'~ 'Consumo responsable',
    Temas== 'P5.7.equipo'~ 'El trabajo en equipo',
    Temas== 'P5.8.ddhh'~ 'Derechos Humanos',
    Temas== 'P5.9.probciudad.'~ 'Poblemas de mi ciudad y mi barrio',
    Temas== 'P5.10.ods'~ 'Los ODS')) |>
  ggplot(aes(x=Temas,
               y=Punt.Media,
               fill= str_wrap(Temas, width = 20)))+
    geom_bar(stat = "identity")+
    geom_text(aes(label=Punt.Media), vjust=2,size=5, colour="white")+
    ggtitle('Puntuaciones medias')+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 12))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="bottom")+
    theme(axis.text.x = element_blank())+
    guides(fill=guide_legend(title = NULL,ncol=5))

layout <- "
AAAAA
AAAAA
AAAAA
#BBB#
"
pr5a + pr5b +

  plot_layout(design = layout) +
     plot_annotation(title = 'Temáticas sobre las que se ha trabajado',
                   caption = textopiePrim,
                   theme = theme(plot.title = element_text(size = 18, 
                                                           face = 'bold',
                                                           colour = 'dodgerblue3',
                                                           hjust = 0.5),
                                 plot.caption = element_text(hjust = 0)))

5. Python


# Método iterativo en foor loop

tit=['Igualdad mujeres y hombres', # Títols dels plots
'Cuidado de la naturaleza',
'La diversidad',
'La paz',
'La justicia',
'Consumo responsable',
'El trabajo en equipo',
'Derechos Humanos',
'Poblemas de mi ciudad y mi barrio',
'Los ODS']

cols = 5
rows = 2

cm= sns.color_palette("mako", 5) # Paleta: important espifica el nombre màxim de bins


fig = plt.figure( figsize=(12, 6))

for i, col in enumerate(pydat.columns[5:15]):

    ax=fig.add_subplot(rows,cols,i+1)
    sns.histplot(x = pydat[col],bins=5, ax = ax).set(ylabel=None, xlabel=None)
    sns.set_context(rc = {'patch.linewidth': 0.0})
    sns.despine(top=True, right=True)
    ax.axvline(x = pydat[col].mean(),color = "orange",lw=3, ls='--')
    #ax.set(title=tit[i])
    ax.set_title(tit[i], fontsize=10)

    for bin_,k in zip(ax.patches,cm):
        bin_.set_facecolor(k)
 


#fig.tight_layout()
fig.suptitle('Temáticas sobre las que se ha trabajado: puntuaciones',size=18, c='slateblue',weight='bold')

plt.show()


fig, ax = plt.subplots(figsize=(12, 4))
s= pd.Series(tit)

s = s.str.wrap(12)

dfp5 = pydat.iloc[:,5:15]
dfp5.columns = s

# Importante, se hace un pivot longer, poniendo las variables como rows.
media = dfp5.stack().reset_index() 
media.columns = ['level_0','var1', 'value']
media= media.drop('level_0', axis=1)
media= media.groupby('var1').mean().reset_index()

# Cuatro líneas de código para mantener el orden de las variables como en los anteriores puntos
s= s.to_frame()
s.columns= ['var2']
media= pd.merge(s, media,left_on='var2',right_on='var1',how='outer')
media= media.drop('var1', axis=1)

sns.barplot(x='var2', y= 'value',data=media, ci=None).set(ylabel='Puntuación', xlabel=None)
sns.despine(top=True, right=True)
plt.title('Temáticas sobre las que se ha trabajado: puntuaciones medias',
          weight= 'bold',size=18, c='slateblue')

# add the annotation
ax.bar_label(ax.containers[-1], fmt= '%.2f', label_type='center',c='white', size= 12, weight= 'bold')

6. Qué opinas sobre las actividades anteriormente mencionadas (en una frase):

prim %>% 
  select(P6.opinas.actividades) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P6.opinas.actividades='')) %>% 
  add_header_lines(values = "Opiniones") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

APRENDIZAJES

7. A través de estas actividades aprendí: (desplegables, respuestas múltiples)

A trabajar en grupo / Conocer la realidad de nuestro mundo y de nuestro entorno Ser responsables de lo que hacemos / A tomar decisiones y trabajar en conjunto para buscar soluciones / A hacer un servicio a la comunidad para mejorar un problema / A cuidar nuestro planeta y a todas las personas

# Para generar un cuadro general de frecuencias de respuestas múltiples pero sin desagregar

prim7_2 <- prim %>% filter(P7.aprend != "")

pr7a <- data.frame(table(unlist(str_split(prim$P7.aprend, ";")))) %>% 
  mutate(Porcentaje=Freq/nrow(prim)) %>%
  ggplot(aes(x=Var1, y=Freq, fill = str_wrap(Var1, width = 35)))+
  geom_bar(stat = "identity")+
  geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=1,size=5, colour= "white")+
  #scale_fill_discrete(name="")+
  geom_hline(aes(yintercept= mean(Freq)),colour= 'orange',lwd=1, linetype=2)+
  geom_text(aes(x=2,y = mean(Freq) + 0.1,
                 label= paste('Promedio menciones= ',round(mean(Freq),1))),
             color="orange", size=5,fontface="bold")+
    ggtitle("A través de estas actividades aprendí:")+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="bottom")+
    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    theme(legend.position = "bottom")+
    guides(fill=guide_legend(title = NULL,ncol=3))+
    scale_fill_brewer(palette="Dark2")

# Crea una lista con número de objetos iguales en todos los miembtos para que quepa en dataframe: si no se hace así el dataframe da error porque el número de objetos  puede ser difrentes

# El max número de objetos de la lista creada por strsplit()
max <- max(unlist(lapply(
  strsplit(prim7_2$P7.aprend,";"),length))) 

# Se igualan los número de objetos en la lista (las diferencia se rellena con "".
lista <- lapply(strsplit(prim7_2$P7.aprend,";"),  
                function(x) c(x, rep("", max-length(x)))
                )

quadre <- cbind(prim7_2[,2],t(as.data.frame(lista))) %>% # Crea y fusiona data frame
  as.data.frame()
rownames(quadre) <- NULL                                    # Elimina row names

quadre <- pivot_longer(quadre,cols = 2:length(quadre), names_to = "resp") %>%
  group_by(V1, value) %>% 
  summarise(n=n()) %>%
  filter(value != "") %>% 
  left_join(TabCEducatPrim[,c(1,2)], by= c("V1"="P1.centro")) |> 
  mutate(Porcentaje= n.x/n.y)

hline_mean <- quadre |> group_by(V1) |> 
  summarise(hl= sum(n.x)/length(unique(quadre$value))) 

pr7b <-ggplot(quadre, aes(x=value,y=n.x,fill=value))+
    geom_bar(stat = "identity")+
    facet_wrap(~V1)+
    geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=1,size=4, 
              colour= 'white')+
    geom_hline(data = hline_mean,aes(yintercept= hl),
               colour= 'orange',lwd=1, linetype=2)+
    geom_text(data= hline_mean, aes(x=2,y = hl + 0.1,
              label= paste('Promedio menciones x centro= ',hl)),
              inherit.aes = FALSE,
              color="orange", size=5,fontface="bold")+
    ggtitle("Segmentación de las respuestas por centro educativo")+
    ylab("")+
    xlab("")+
    theme_classic()+
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="bottom")+
    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    theme(legend.position = "none")+
    guides(fill=guide_legend(ncol=3))+
    scale_fill_brewer(palette="Dark2")

pr7a / pr7b +
   plot_annotation(
     title = 'Identificación de aprendizajes percibidos',
                   caption = textopiePrim,
                   theme = theme(plot.title = element_text(size = 18, 
                                                           face = 'bold',
                                                           colour = 'dodgerblue3',
                                                           hjust = 0.5),
                                 plot.caption = element_text(hjust = 0)))

7. Python


fig, ax = plt.subplots(figsize=(12, 4))

p7 = pydat['P7.aprend'].str.split(pat= ';', expand=True).stack().reset_index()
p7.columns= ['level_0', 'level_1', 'apr']
p7 = p7.drop(['level_0', 'level_1'], axis= 1)

def my_agg(x):
    names = {
        'num': len(x),
        'percent': (len(x) / len(pydat)*100)}
    return pd.Series(names, index=[ 'num', 'percent'])

aprend= p7.groupby('apr').apply(my_agg)

aprend= aprend.reset_index()
aprend['apr'] = aprend['apr'].str.wrap(20)
wmean = round(sum(aprend['num']*aprend['percent']) / sum(aprend['num'])) # media ponderada

sns.barplot(x='apr', y= 'percent',data= aprend, ci=None).set(ylabel='Porcentaje', xlabel=None)
sns.despine(top=True, right=True)
plt.axhline(y = wmean, color = "orange",lw=3, ls='--')
plt.title('A través de estas actividades aprendí:',
          weight= 'bold',size=18, c='slateblue')
# add the annotation
ax.bar_label(ax.containers[-1], fmt='%.0f%%', label_type='center',c='white', size= 12, weight= 'bold')


#warnings.filterwarnings('ignore')

#plt.figure(figsize=(10, 10)) 
#fig, ax = plt.subplots(figsize=(14, 10))
#fig = plt.figure( figsize=(cols*5, rows*5))

p7b = pydat[['P2.sexo','P7.aprend']]
p7b['P7.aprend'] = p7b['P7.aprend'].str.split(pat= ';')#.stack().reset_index()
## <string>:1: SettingWithCopyWarning: 
## A value is trying to be set on a copy of a slice from a DataFrame.
## Try using .loc[row_indexer,col_indexer] = value instead
## 
## See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
p7b = p7b.explode('P7.aprend', ignore_index=True).reset_index(drop=True)

p7b = p7b.groupby(['P2.sexo','P7.aprend']).size().reset_index()
p7b.columns = ['sexo','aprend', 'n']

p7b= pd.merge(p7b, tabSexPy, how= 'left', left_on='sexo', right_on= 'sexo').drop(['Porcentaje'], axis=1)
p7b['percent'] = p7b['n_x']/p7b['n_y']*100
p7b['aprend'] = p7b['aprend'].str.wrap(15)

# Defining weighted means to create hlines
def my_agg3(x):
    names = {
        'prod': (x['n_x']*x['percent']).sum(),
        'num':  x['n_x'].sum()}
    return pd.Series(names, index=[ 'prod','num'])

wdm= p7b.groupby('sexo').apply(my_agg3)
wdm['wdm']= round(wdm['prod']/wdm['num'],1)
wdm= wdm.drop(['prod','num'], axis=1).reset_index()

# PLOTTING
g1 = sns.FacetGrid(p7b, col='sexo', hue='aprend', col_wrap=2, height=5,aspect=1.5)\
    .set(ylim=(0,100))
g1.map(sns.barplot,'aprend', 'percent', order=p7b.aprend.unique()).set_xticklabels([])\
    .set(xlabel=None)\
    .add_legend(loc=1)\
    .legend.set_title(None)

axes = g1.axes.flatten()
axes[0].set_title(axes[0].get_title()[7:],y=1, size=16)
axes[1].set_title(axes[1].get_title()[7:],y=1, size=16)
 

for ax in g1.axes:
    for p in ax.patches:
             ax.annotate("%.1f" % p.get_height()+'%', (p.get_x() + p.get_width() / 2., p.get_height()),
                 ha='center', va='center', fontsize=11, color='white',weight= 'bold', xytext=(0, -10),
                 textcoords='offset points')

for i in range(len(wdm)):
    axes[i].axhline(y = wdm.iloc[i,1], color = "orange",lw=3, ls='--')
    axes[i].text(0.2, wdm.iloc[i,1]+3, 'Promedio menciones por género '+str(wdm.iloc[i,1])+'%',
                 size=12, weight= 'bold', c='orange')
        

g1.fig.suptitle('Segmentación de las respuestas por género',y=1.05, weight= 'bold', size=18) 

plt.show()

7. Plotly

library(plotly)

prim7_2 <- prim %>% filter(P7.aprend != "")

# Crea una lista con número de objetos iguales en todos los miembtos para que quepa en dataframe: si no se hace así el dataframe da error porque el número de objetos  puede ser difrentes

# El max número de objetos de la lista creada por strsplit()
max <- max(unlist(lapply(
  strsplit(prim7_2$P7.aprend,";"),length))) 

# Se igualan los número de objetos en la lista (las diferencia se rellena con "".
lista <- lapply(strsplit(prim7_2$P7.aprend,";"),  
                function(x) c(x, rep("", max-length(x)))
                )

quadre <- cbind(prim7_2[,2:3],t(as.data.frame(lista))) %>% # Crea y fusiona data frame
  as.data.frame()
rownames(quadre) <- NULL # Elimina row names

quadre <- pivot_longer(quadre,cols = 3:length(quadre),
                       names_to = "resp") %>%
  group_by(P1.centro, value, P2.sexo) %>% 
  summarise(n=n()) %>%
  filter(value != "") %>% 
  left_join(TabCEducatPrim[,c(1,2)], by= c("P1.centro"="P1.centro")) %>% 
  mutate(Porcentaje= n.x/n.y) |> 
  filter(P2.sexo != 'Prefiero no decirlo') # ojo aquest filtre

text <- paste('Centro: ',quadre$P1.centro, # Texto para la etiqueta
              '\nGénero: ', quadre$P2.sexo,
              '\nAprendizajes: ', quadre$value,
              '\nFrecuencia: ', quadre$n.x) 

hline_mean1 <- quadre |> group_by(P1.centro) |> 
  summarise(hl= sum(n.x)/length(unique(quadre$value))) 

p<-    ggplot(quadre,aes(x=str_wrap(value, 15),
                         y=n.x,
                         fill=P2.sexo,
                         text=text))+
    geom_bar(stat = "identity", position= 'stack')+
    facet_wrap(~P1.centro)+
    geom_hline(data = hline_mean1,aes(yintercept= hl),
               colour= 'orange',lwd=0.8, linetype=2)+
    geom_text(data=hline_mean1, aes(x=2, y=hl+0.1, 
                  label= paste('Promedio menciones por centro= ',hl)),
                  inherit.aes= FALSE,
                  color="orange", size=3,fontface="bold")+
    #geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=1,size=4, 
     #         colour= 'white')+
    ggtitle("Segmentación de las respuestas por centro y género")+
    ylab("")+
    xlab("")+
    theme_classic()+
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="bottom")+
    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    theme(legend.position = "none")+
    #guides(fill=guide_legend(title = NULL, ncol=2))+
    scale_fill_brewer(palette="Dark2")
ggplotly(p, 
         tooltip = 'text') |> 
  style(hoverlabel = list(bgcolor = "white",
                          bordercolor = "#77777",
                          font = list(color  = '#77777'),
                          align = "left",   # THIS IS NOT WORKING
                          orientation = "h" # THIS IS NOT WORKING
                          )
        )

EVALUACIÓN: IOV3 R1.

Al menos el 80% del alumnado participante (al menos el 55% mujeres) desarrolla actitudes de equidad y corresponsabilidad frente a las violencias machistas.

LÍNEA DE BASE: IOV2 R1.

Al menos el 80% de las y los titulares de derechos participantes (alumnado, al menos el 55% mujeres) desarrollan actitudes de igualdad de género y en la diversidad y de corresponsabilidad frente a las violencias machistas y discursos de odio.

ACTITUDES SOBRE VIOLENCIA MACHISTA

8. [2020: P14] ¿Cuáles de las siguientes situaciones consideras que son violencias machistas?. Puedes elegir las opciones que consideres. (Desplegable con múltiples opciones)

Que no escuchen e interrumpan a las niñas cada vez que hablan / Comentarios y bromas sobre el cuerpo o vestimenta de las niñas / Apartar a las niñas en el patio porque los niños tienen que jugar a futbol / Comentarios y chistes machistas / Que las mujeres sean las que se tienen que encargar de las tareas de la casa

library(ggpubr)
prim8_2 <- prim %>% filter(P8.violencias.machistas != "")

pr8a <- data.frame(table(unlist(str_split(prim$P8.violencias.machistas, ";")))) %>% 
  mutate(Porcentaje=Freq/nrow(prim)) %>%
  ggplot(aes(x=Var1, y=Porcentaje, fill = str_wrap(Var1, width = 25)))+
  geom_bar(stat = "identity")+
  scale_y_continuous(labels = percent, limits = 0:1)+
  geom_text(aes(label=percent(Porcentaje,0.1)), vjust=1,size=5, colour= "white")+
  ggtitle("¿Cuáles de las siguientes situaciones \nconsideras que son violencias machistas?")+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="none")+
    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    #guides(fill=guide_legend(title = NULL,ncol=4))+
    scale_fill_brewer(palette="Dark2")


viol20 <- prim2020 |> mutate(P14.Violencia.machista= 
                               if_else(grepl('Todas las anteriores', prim2020$P14.Violencia.machista),'Todas las anteriores',
                                       if_else(
                                         grepl(
                                         'Nada de lo anterior me parece violencia machista',prim2020$P14.Violencia.machista),
                                         'Nada de lo anterior me parece violencia machista', 
                                         P14.Violencia.machista
  )))
pr8b<- data.frame(table(unlist(str_split(viol20$P14.Violencia.machista, ";")))) %>% 
    filter(Var1!='') |> 
    filter(Var1!='Nada de lo anterior me parece violencia machista') |> 
    mutate(TodasAnteriores= 80) |> 
    mutate(tot= Freq+TodasAnteriores) |> 
    filter(Var1!= 'Todas las anteriores') |> 
    mutate(Porcentaje=tot/nrow(viol20)) %>%
  ggplot(aes(x=Var1, y=Porcentaje, fill = str_wrap(Var1, width = 25)))+
  geom_bar(stat = "identity")+
  scale_y_continuous(labels = percent, limits = 0:1)+
  geom_text(aes(label=percent(Porcentaje,0.1)), vjust=1,size=5, colour= "white")+
  ggtitle("Comparación con la encuesta de 2020")+
    ylab("")+
    xlab("")+
    theme_classic() +
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+

    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    theme(legend.position = "none")+
    #guides(fill=guide_legend(title = NULL,ncol=3))+
    scale_fill_brewer(palette="Dark2")


# Crea una lista con número de objetos iguales en todos los miembtos para que quepa en dataframe: si no se hace así el dataframe da error porque el número de objetos  puede ser difrentes



# El max número de objetos de la lista creada por strsplit()


max <- max(unlist(lapply(
  strsplit(prim8_2$P8.violencias.machistas,";"),length))) 

# Se igualan los número de objetos en la lista (las diferencia se rellena con "".
lista <- lapply(strsplit(prim8_2$P8.violencias.machistas,";"),  
                function(x) c(x, rep("", max-length(x)))
                )

quadre <- cbind(prim8_2[,3],t(as.data.frame(lista))) %>% # Crea y fusiona data frame
  as.data.frame()
rownames(quadre) <- NULL                                    # Elimina row names

quadre <- pivot_longer(quadre,cols = 2:length(quadre),
             names_to = "menjar") %>%
  group_by(V1, value) %>% 
  summarise(n=n()) %>%
  filter(value != "") %>% left_join(TabGenPrim[,c(1,2)], 
                                    by= c("V1"="P2.sexo")) %>% 
  mutate(Porcentaje= n.x/n.y) |> 
  filter(V1 != 'Prefiero no decirlo') # ojo al filtre
  
pr8c <-ggplot(quadre,aes(x=value,y=n.x,fill=str_wrap(value, width=25)))+
    geom_bar(stat = "identity")+
    facet_wrap(~V1)+
    geom_text(aes(label=scales::percent(Porcentaje,1)), vjust=1,size=4, 
              colour= 'white')+
    ggtitle("Segmentación de las respuestas por sexo")+
    ylab("")+
    xlab("")+
    theme_classic()+
    theme(plot.title = element_text(hjust=0.5, face = "bold", size = 14))+
    theme(axis.title.x = element_text(face = "bold", size = 13))+
    theme(axis.title.y = element_text(face = "bold", size = 13))+
    theme(legend.position="bottom")+
    guides(fill=guide_legend(title = NULL,ncol=5))+
    theme(plot.caption = element_text(size = 10,hjust = 0))+
    theme(axis.text.x = element_blank())+
    scale_fill_brewer(palette="Dark2")

plot <- ggarrange((pr8a + pr8b) / pr8c, ncol=1, nrow=1, common.legend = TRUE, legend="bottom")
annotate_figure(plot, top = text_grob("Actitudes sobre violencia machista", 
               color = "dodgerblue3", face = "bold", size = 18))

ACTITUDES DE EQUIDAD

9. [2020: P10] Con una palabra, responsabilizarme de las tareas de casa es:

# Create the Text Corpus
corpusP9 = Corpus(VectorSource(prim$P9.tareas.casa))

# Elimina mayusculas
corpusP9 = tm_map(corpusP9,PlainTextDocument)
corpusP9 = tm_map(corpusP9, tolower)

# Elimina interpuncción
corpusP9 <- tm_map(corpusP9, removePunctuation)

# Elimina conjunciones y preposiciones (spanish)
corpusP9 <- tm_map(corpusP9, removeWords, stopwords("spanish"))

# Elimina números
corpusP9 = tm_map(corpusP9, removeNumbers)


# Elimina espacios en blanco en exceso.
corpusP9 = tm_map(corpusP9,stripWhitespace)


# Create the term document matrix
TDM.P9 <- TermDocumentMatrix(corpusP9)
matriz.P9 <- as.matrix(TDM.P9)
f.P9 <- sort(rowSums(matriz.P9),decreasing=TRUE)
dat.P9 <- data.frame(palabra = names(f.P9),freq=f.P9)

dat.P9 <- dat.P9 %>%
    filter(!palabra %in% c("través", "tener", "gran", "aunque", "alguien", "veo", "lugar", "hago", "ser", "hacer", "buen", "mejor", "ello", "pueden", "debemos", "todas", "nadie", "hagan", "así", "mas", "medio"))%>%
    mutate(palabra = if_else(palabra== "mundo", "planeta", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudas", "ayuda", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudo", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayuda", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ambiente", "medio ambiente", palabra)) %>%
    group_by(palabra) %>%
    summarise(freq = sum(freq)) %>%
    arrange(desc(freq))

# Nube de palabras
wordcloud(words = dat.P9$palabra, freq = dat.P9$freq, random.order=TRUE,scale=c(3,.6),
          max.words = 80, min.freq = 4,rot.per = .3, colors = brewer.pal(name = "Dark2", n = 12))
text(x=-0.3,y=0, textopiePrim, cex=0.5, pos=4)

10. [2020: P8] Con una sola palabra, luchar porque todas las personas tengamos los mismos derechos, a pesar de nuestras diferencias es:

# Create the Text Corpus
corpusP10 = Corpus(VectorSource(prim$P10.mismos.derechos))

# Elimina mayusculas
corpusP10 = tm_map(corpusP10,PlainTextDocument)
corpusP10 = tm_map(corpusP10, tolower)

# Elimina interpuncción
corpusP10 <- tm_map(corpusP10, removePunctuation)

# Elimina conjunciones y preposiciones (spanish)
corpusP10 <- tm_map(corpusP10, removeWords, stopwords("spanish"))

# Elimina números
corpusP10 = tm_map(corpusP10, removeNumbers)


# Elimina espacios en blanco en exceso.
corpusP10 = tm_map(corpusP10,stripWhitespace)


# Create the term document matrix
TDM.P10 <- TermDocumentMatrix(corpusP10)
matriz.P10 <- as.matrix(TDM.P10)
f.P10 <- sort(rowSums(matriz.P10),decreasing=TRUE)
dat.P10 <- data.frame(palabra = names(f.P10),freq=f.P10)

dat.P10 <- dat.P10 %>%
    filter(!palabra %in% c("través", "tener", "gran", "aunque", "alguien", "veo", "lugar", "hago", "ser", "hacer", "buen", "mejor", "ello", "pueden", "debemos", "todas", "nadie", "hagan", "así", "mas", "medio"))%>%
    mutate(palabra = if_else(palabra== "mundo", "planeta", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudas", "ayuda", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudo", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayuda", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ambiente", "medio ambiente", palabra)) %>%
    group_by(palabra) %>%
    summarise(freq = sum(freq)) %>%
    arrange(desc(freq))

# Nube de palabras
wordcloud(words = dat.P10$palabra, freq = dat.P10$freq, random.order=TRUE,scale=c(3,.6),
          max.words = 80, min.freq = 4,rot.per = .3, colors = brewer.pal(name = "Dark2", n = 12))
text(x=-0.3,y=0, textopiePrim, cex=0.5, pos=4)

EVALUACIÓN: :IOV6 R2.

Al menos el 80% del alumnado participante (al menos 55% mujeres) en la formación y la práctica de experiencias de APS u otras metodologías coeducativas transformadoras desarrolla actitudes de solidaridad y compromiso local y global.

LÍNEA DE BASE: IOV4 R2.

Al menos el 80% de los y las titulares de derechos (alumnado, al menos 50% mujeres) participantes en las experiencias de APSC, laboratorios u otras propuestas metodológicas, desarrolla habilidades socioemocionales y actitudes de solidaridad, equidad, cuidados de las personas y el planeta, inclusión de las diversidades y compromiso local/global.

HABILIDADES SOCIOEMOCIONALES Y ACTITUDES DE SOLIDARIDAD

Completa las frases:

11. [2020: P09] Con una sola palabra, cuando veo que insultan un/a compañero/a, me siento:

# Create the Text Corpus
corpusP11 = Corpus(VectorSource(prim$P11.insultan))

# Elimina mayusculas
corpusP11 = tm_map(corpusP11,PlainTextDocument)
corpusP11 = tm_map(corpusP11, tolower)

# Elimina interpuncción
corpusP11 <- tm_map(corpusP11, removePunctuation)

# Elimina conjunciones y preposiciones (spanish)
corpusP11 <- tm_map(corpusP11, removeWords, stopwords("spanish"))

# Elimina números
corpusP11 = tm_map(corpusP11, removeNumbers)


# Elimina espacios en blanco en exceso.
corpusP11 = tm_map(corpusP11,stripWhitespace)


# Create the term document matrix
TDM.P11 <- TermDocumentMatrix(corpusP11)
matriz.P11 <- as.matrix(TDM.P11)
f.P11 <- sort(rowSums(matriz.P11),decreasing=TRUE)
dat.P11 <- data.frame(palabra = names(f.P11),freq=f.P11)

dat.P11 <- dat.P11 %>%
    filter(!palabra %in% c("través", "tener", "gran", "aunque", "alguien", "veo", "lugar", "hago", "ser", "hacer", "buen", "mejor", "ello", "pueden", "debemos", "todas", "nadie", "hagan", "así", "mas", "medio"))%>%
    mutate(palabra = if_else(palabra== "mundo", "planeta", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudas", "ayuda", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudo", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayuda", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ambiente", "medio ambiente", palabra)) %>%
    group_by(palabra) %>%
    summarise(freq = sum(freq)) %>%
    arrange(desc(freq))

# Nube de palabras
wordcloud(words = dat.P11$palabra, freq = dat.P11$freq, random.order=TRUE,scale=c(3,.6),
          max.words = 80, min.freq = 4,rot.per = .3, colors = brewer.pal(name = "Dark2", n = 12))
text(x=-0.3,y=0, textopiePrim, cex=0.5, pos=4)

12. Completa la frase: Cuando ayudamos a otra persona lo hacemos porque:


prim %>% 
  select(P12.ayudamos) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P12.ayudamos='')) %>% 
  add_header_lines(values = "Respuestas") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

13. Para ti, ¿Cuál es el problema más importante de tu escuela?:


prim %>% 
  select(P13.problema.escuela) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P13.problema.escuela='')) %>% 
  add_header_lines(values = "Respuestas") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

ACTITUDES DE EQUIDAD Y COMPROMISO LOCAL Y GLOBAL

14. [2020: P11] Reciclar es (con una sola palabra):

# Create the Text Corpus
corpusP14 = Corpus(VectorSource(prim$P14.reciclar))

# Elimina mayusculas
corpusP14 = tm_map(corpusP14,PlainTextDocument)
corpusP14 = tm_map(corpusP14, tolower)

# Elimina interpuncción
corpusP14 <- tm_map(corpusP14, removePunctuation)

# Elimina conjunciones y preposiciones (spanish)
corpusP14 <- tm_map(corpusP14, removeWords, stopwords("spanish"))

# Elimina números
corpusP14 = tm_map(corpusP14, removeNumbers)


# Elimina espacios en blanco en exceso.
corpusP14 = tm_map(corpusP14,stripWhitespace)


# Create the term document matrix
TDM.P14 <- TermDocumentMatrix(corpusP14)
matriz.P14 <- as.matrix(TDM.P14)
f.P14 <- sort(rowSums(matriz.P14),decreasing=TRUE)
dat.P14 <- data.frame(palabra = names(f.P14),freq=f.P14)

dat.P14 <- dat.P14 %>%
    filter(!palabra %in% c("través", "tener", "gran", "aunque", "alguien", "veo", "lugar", "hago", "ser", "hacer", "buen", "mejor", "ello", "pueden", "debemos", "todas", "nadie", "hagan", "así", "mas", "medio"))%>%
    mutate(palabra = if_else(palabra== "mundo", "planeta", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudas", "ayuda", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayudo", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ayuda", "ayudar", palabra)) %>%
    mutate(palabra = if_else(palabra== "ambiente", "medio ambiente", palabra)) %>%
    group_by(palabra) %>%
    summarise(freq = sum(freq)) %>%
    arrange(desc(freq))

# Nube de palabras
wordcloud(words = dat.P14$palabra, freq = dat.P14$freq, random.order=TRUE,scale=c(3,.6),
          max.words = 80, min.freq = 4,rot.per = .3, colors = brewer.pal(name = "Dark2", n = 12))
text(x=-0.3,y=0, textopiePrim, cex=0.5, pos=4)

15. Para ti, ¿cuál es el problema más importante de tu barrio?:


prim %>% 
  select(P15.barrio) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P15.barrio='')) %>% 
  add_header_lines(values = "Respuestas") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

16. Para ti, ¿cuál es el problema más importante de tu ciudad?:


prim %>% 
  select(P16.ciudad) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P16.ciudad='')) %>% 
  add_header_lines(values = "Respuestas") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")

17. Para ti, ¿cuál es el problema más importante del mundo?:

prim %>% 
  select(P17.mundo) %>% 
  flextable() |> 
  width(width = 5) %>% 
  set_header_labels(values = list(P17.mundo='')) %>% 
  add_header_lines(values = "Respuestas") %>% 
  footnote(i = 1, j = 1,
               value = as_paragraph(textopiePrim),
               ref_symbols = c(""),
               part = "header", inline = TRUE) %>% 
  theme_vanilla() %>% italic(part = "footer")