Home > OS >  R Problems using haven::as_factor
R Problems using haven::as_factor

Time:08-10

The data has answers of 1, 2 and NA for FP. I am trying to set up the data for a ggplot box plot, and need the factors so it can use FP for the x values in the plot to split them into separate plots. I then want to rename to NAs to OM, and ideally rename 1 and 2 to character values as well.

c_plot <- dataset %>%
  select(XCD, FP) %>%
  filter(XCD > 0) %>%
  haven::as_factor(FP, levels = "labels") %>%
  mutate(FP = ifelse(is.na(FP, OM, FP)) %>%

The error is:

Error in force(ordered) : object 'FTPT' not found
Error:
! Arguments in `...` must be used.
x Problematic argument:
* ..1 = FP

How do I get it to correctly produce the data I need?

CodePudding user response:

Without seeing your data it's hard to tell exactly what's going wrong, but you could try something like mutate(abc = haven::as_factor(col_name)) e.g.:

iris %>% 
  mutate(abc = haven::as_factor(Sepal.Length))

#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species abc
# 1            5.1         3.5          1.4         0.2     setosa 5.1
# 2            4.9         3.0          1.4         0.2     setosa 4.9
# 3            4.7         3.2          1.3         0.2     setosa 4.7
# 4            4.6         3.1          1.5         0.2     setosa 4.6
# 5            5.0         3.6          1.4         0.2     setosa   5

Also, the last line should look like this (note the placement of the parentheses)

  mutate(FP = ifelse(is.na(FP), OM, FP)) 
  • Related