将具有NAs的数值变量进行转换和四舍五入。

huangapple go评论92阅读模式
英文:

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 &lt;- fab_2023 %&gt;%
  mutate_at(vars(Total_score_2023:MA_Combined_Social_2021), ~ ifelse(is.na(.), NA, as.numeric(.)))

fab_2023 &lt;- fab_2023 %&gt;%
  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 |&gt;
  mutate(across(Total_score_2023:MA_Combined_Social_2021, ~ round(as.numeric(.), 2))) 
英文:
library(dplyr)

fab_2023 |&gt;
  mutate(across(Total_score_2023:MA_Combined_Social_2021, ~ round(as.numeric(.), 2))) 

huangapple
  • 本文由 发表于 2023年8月4日 03:46:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76831212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定