英文:
Converting and Rounding Numeric Variables with NAs
问题
我正在使用名为 fab_2023
的数据集,这个数据集是我从Excel中导入的。在数据集中的变量中,我需要将某些变量转换为数值格式。然而,这些变量包含缺失值(NAs)。此外,原始的数值值有超过两位小数,我的目标是将这些数值值精确地四舍五入到两位小数。我所做的如下:
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)))
基本上,我想将从Total_score_2023到MA_Combined_Social变量的所有变量转换为数值变量,并四舍五入到两位小数。当我这样做时,似乎确实按照我想要的方式转换了数据,但然后我遇到了以下错误消息:
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.
请问我是否做错了什么?谢谢!
英文:
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!
答案1
得分: 1
library(dplyr)
fab_2023 |>
mutate(across(Total_score_2023:MA_Combined_Social_2021, ~ round(as.numeric(.), 2)))
英文:
library(dplyr)
fab_2023 |>
mutate(across(Total_score_2023:MA_Combined_Social_2021, ~ round(as.numeric(.), 2)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论