Home > other >  How to assign names to a numeric vector in R?
How to assign names to a numeric vector in R?

Time:10-08

This should be a really straightforward thing, however I am getting trouble assigning names to a numeric vector.

My code is as follows:

library(tidyverse)
library(haven)
library(labelled)

CIS = read_spss("CISData.sav") %>%
  mutate(
    RECUERDO = to_factor(RECUERDO))

include = c(21, 2, 4, 1, 18)

Voters <- ggplot(CIS %>% filter(RECUERDO %in% include), aes(x = RECUERDO))  
  geom_bar(fill = "Brown")  
  xlab("Voting Preference in 2019 Spanish General Elections")  
  ylab("Count")

Voters

It works perfectly fine and it produces the following graph:

Graph

However, what I wish to achieve is to have in the graph "Unidas Podemos" instead of "21", "PSOE" instead of "2", "Ciudadanos" instead of "4", "PP" instead of "1", and "VOX" instead of "18".

So far, I have tried setNames in stats, set_names in magrittr, as well as directly assigning the variables; but nothing of this has worked.

Any help would be much appreciated!

Many thanks in advance!

CodePudding user response:

OK, I've found the correct answer on how to do it! Here it is:

#Composition of respondents according to which political party they voted for in 2019 Spanish General Elections 

library(tidyverse)
library(haven)
library(labelled)

CIS = read_spss("CISData.sav") %>%   
    mutate(RECUERDO = to_factor(RECUERDO)) %>%  
    filter(RECUERDO %in% c(21, 2, 4, 1, 18))

CIS$RECUERDO = factor(CIS$RECUERDO, labels=c("PP", "PSOE", "Ciudadanos", "VOX", "Unidas Podemos"))

Voters <- ggplot(CIS, aes(x = RECUERDO))  
  geom_bar(fill = "Brown")  
  xlab("Voting Preference in 2019 Spanish General Elections")  
  ylab("Count")

Voters

CodePudding user response:

Set the correct factor names before you plot it. If you don't want to change the existing variable, you can always create a new one instead, but I'm just renaming your original variable below. The following should work. Your code is not reproducible, but ggplot plots factors in the order that they are in, so I'm assuming the order on the plot is what would be returned by levels(CIS$RECUERDO) before renaming the levels.

CIS = read_spss("CISData.sav") %>%  
    filter(RECUERDO %in% c(21, 2, 4, 1, 18)) %>%
    mutate(RECUERDO = to_factor(RECUERDO))

# rename levels of RECUERDO
# make sure the order of the new names matches the order of old factor names 
levels(CIS$RECUERDO) <- c("PP", "PSOE", "Ciudadanos", "VOX", "Unidas Podemos")
  • Related