R 无法识别丢失的数据

发布于 2025-01-17 12:58:00 字数 1432 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

围归者 2025-01-24 12:58:00

您可以使用以下代码将所有空值替换为 NA

library(dplyr)
your_data_with_NA <- your_data %>% 
  mutate_all(na_if, "")

You could replace all the empty values with NA by using the following code:

library(dplyr)
your_data_with_NA <- your_data %>% 
  mutate_all(na_if, "")
请恋爱 2025-01-24 12:58:00

最简单的方法通常是在导入数据时解决此问题。大多数用于导入数据的函数都有一些参数来指定哪些值应解释为 NA,例如:

  • read.csv 等:na.strings
  • readr::read_csv 等:na
  • readxl::read_excel 等:na

只需设置"" 的这个参数, " " 或 R 不解释为 NA 的任何值。

如果这不适合您,您可以使用 NA 替换空白值:

library(dplyr)

df %>% 
  mutate(
    across(
      everything(),
      ~na_if(.x, "")
    )
  )

请注意,mutate(across(everything())) 已取代 mutate_all,但 做同样的事情


数据

df <- mtcars %>% head()

df[1, 1] <- ""

The easiest is often to fix this when importing your data. Most functions for importing data has some argument to specify which values should be interpreted as NA, for example:

  • read.csv and the like: na.strings
  • readr::read_csv and the like: na
  • readxl::read_excel and the like: na

Just set this argument to "", " " or to any value that is not interpreted as NA by R.

If this is not an option for you, you can replace the blank values with NA using:

library(dplyr)

df %>% 
  mutate(
    across(
      everything(),
      ~na_if(.x, "")
    )
  )

Note that mutate(across(everything())) has superseeded mutate_all but does the same.


Data

df <- mtcars %>% head()

df[1, 1] <- ""
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文