Home > Software engineering >  Why am I getting error message, "attribute must be same length as vector" when using mutat
Why am I getting error message, "attribute must be same length as vector" when using mutat

Time:08-17

I am using the following code to create a new variable that codes the characters "*" and "**" within 'pct_met_exceeded' to 0's, so that the new variable, 'simple_met_exceeded', can be interpreted as a number.

TNschools <- TNschools %>% 
mutate(
simple_met_exceed = case_when(
pct_met_exceeded == "*" | pct_met_exceeded == "**" ~ 0,
TRUE ~ pct_met_exceeded))

However, I am getting the error message,

"Error in mutate(): ! Problem while computing simple_met_exceed = case_when(...). Caused by error in names(message) <- `*vtmp*`: ! 'names' attribute [1] must be the same length as the vector [0] Backtrace: 1. TNschools %>% ...7. dplyr::case_when(...) 8. dplyr:::replace_with(...) 9. dplyr:::check_type(val, x, name, error_call = error_call) 10. rlang::abort(msg, call = error_call) ... 15. rlang::cnd_message(c)16. rlang:::cnd_message_format(cnd, ...)17. rlang (local) cli_format(glue_escape(lines))18. rlang:::.rlang_cli_format(x, cli::format_error)19. cli::cli_format(x, .envir = emptyenv()) "

All of the data in the variable pct_met_exceeded seen here is formatted as character, ex. below. Thanks in advance for any clarity you can provide.

pct_met_exceeded
*
**
5.9
*
6.7

CodePudding user response:

I belive that the issue here is that your column currently parses as character instead of numeric due to the stars. Try fixing your code to:

TNschools %>%
  mutate(
simple_met_exceed = readr::parse_number(case_when(
pct_met_exceeded == "*" | pct_met_exceeded == "**" ~ "0",
TRUE ~ pct_met_exceeded)))

# # A tibble: 5 × 2
#   pct_met_exceeded simple_met_exceed
#   <chr>                        <dbl>
# 1 *                              0  
# 2 **                             0  
# 3 5.9                            5.9
# 4 *                              0  
# 5 6.7                            6.7
  • Related