0

I am working with a dataset called fab_2023, which I imported from Excel. Among the variables in the dataset, I need to convert certain ones into numeric format. However, these variables do contain missing values (NAs). Additionally, the original numeric values have more than two decimal places, and my goal is to round these numerical values to precisely two decimal places. This is what I did:

fab_2023 <- fab_2023 %>%
  mutate_at(vars(Total_score_2023:MA_Combined_Social_2021), ~ ifelse(is.na(.), NA, as.numeric(.)))

fab_2023 <- fab_2023 %>%
  mutate_at(vars(Total_score_2023:MA_Combined_Social_2021), ~ ifelse(is.na(.), NA, round(., 2)))

I basically want to convert all variables from Total_score_2023 to MA_Combined_Social variables to numerical variables and round up to two decimal places. When I do that, it seems it actually does convert the data in the way I want but then I encounter the following error message:

Error in `mutate()`:
! Problem while computing `Total_score_2021 = (structure(function (..., .x = ..1, .y = ..2, . = ..1) ...`.
Caused by error in `round()`:
! non-numeric argument to mathematical function
Run `rlang::last_error()` to see where the error occurred.

Can you please advise me if I am doing something wrong? Thank you!

e. erhan
  • 61
  • 6
  • You do not need to do `ifelse`. `as.numeric(NA)` will return `NA`. Try `as.numeric(c("3", "2.5", NA))`. – LMc Aug 03 '23 at 19:51
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Aug 03 '23 at 19:51
  • @LMc may I ask what 3 and 2.5 stands for? Didn't get your code enough, sorry! – e. erhan Aug 03 '23 at 20:08
  • 1
    They are just character representations of numbers. I was just showing you that you do not need to convert it conditionally (ie `is.na(.), NA, as.numeric(.)`). – LMc Aug 03 '23 at 20:10

1 Answers1

1
library(dplyr)

fab_2023 |>
  mutate(across(Total_score_2023:MA_Combined_Social_2021, ~ round(as.numeric(.), 2))) 
LMc
  • 12,577
  • 3
  • 31
  • 43