Skip to content

Instantly share code, notes, and snippets.

@guidocor
Created April 22, 2019 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guidocor/57c86a0876612453745150e22c413bed to your computer and use it in GitHub Desktop.
Save guidocor/57c86a0876612453745150e22c413bed to your computer and use it in GitHub Desktop.
Análisis Factorial de la simpatía por los políticos en R
Creados para tuitear sobre la encuesta preelectoral y hacer este tuit https://twitter.com/GuidoBCor/status/1120248040848334849
######################################################################
# Functions To Factor Analyze the scale
######################################################################
rm(list=ls()); gc()
options(scipen=20)
if (!require("pacman")) install.packages("pacman")
pacman::p_load("tidyverse", "psych", "haven", "bootnet", "qgraph", "Rmisc", "Hmisc")
# Sacamos del CIS la encuesta
dataset <- read_sav("3242.sav")
# Nos interesan las preguntas de simpatía, asi que vamos por la que empiezan por P11
df = dataset %>% dplyr::select(starts_with("P11"))
colnames(df) <- c("Abascal", "Casado", "Garzón", "Iglesias", "Rivera", "Sánchez")
df$id = 1:nrow(df)
df = gather(df, key = "Simpatía", value = "valoración", 1:6)
df[df$valoración == 99 | df$valoración == 98 | df$valoración == 97, "valoración"] <- NA
df <- spread(df, key = "Simpatía", value = "valoración")
df <- select(df, -id)
df <- df[complete.cases(df),]
parallel <- fa.parallel(df, fa = "fa", fm = "ml", plot = FALSE)
factores = fa(df, nfactors = 2, rotate = "oblimin", fm = "ml")
summary(factores)
loadings_efa <- factores$loadings[,1:2] %>% round(2) %>% as.data.frame()
loadings_efa <- loadings_efa %>% rownames_to_column("Político")
#loadings_efa$Item <- toupper(loadings_efa$Item)
loadings_efa_m <- gather(loadings_efa,
key = "Factor",
value = "Carga", 2:3)
loadings_efa_m <- loadings_efa_m %>% arrange(
desc(Carga))
loadings_efa_m$Factor <- ifelse(loadings_efa_m$Factor == "ML1", "Derecha", "Izquierda")
ggplot(loadings_efa_m, aes(Político, Carga, fill=Carga)) +
facet_wrap(~ Factor, nrow=1) + #place the factors in separate facets
geom_bar(stat="identity") + #make the bars
coord_flip() + #flip the axes so the test names can be horizontal
#define the fill color gradient: blue=positive, red=negative
scale_fill_gradient2(name = "Loading",
high = "black", mid = "grey", low = "grey",
midpoint=0.3, guide=F) +
ylim(-.1,1) +
ylab("Carga factorial") + #improve y-axis label
theme_bw(base_size=10) + #use a black-and-white theme with set font size
ggtitle("Cargas factoriales de la puntuación en simpatía de cada lider")
write.csv(df, "simpatia.csv", row.names = F)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment