简体   繁体   中英

How to assign names to a numeric vector in R?

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:

图形

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!

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")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM