首页 > 解决方案 > 我想在读取数据库时用空格更改空白单元格

问题描述

嗨,我正在阅读 excel 文件,在阅读时我想将空白单元格保留为“”,因为阅读后我将单元格的文本“无数据”转换为 NA。

我们对此有什么解决方案吗,我的意思是我不想将数据保留到 NA 并将空白单元格保留到“”空间。

df <- read.xlsx("dir/db.xlsx")
df <- df %>% mutate(across(where(is.character),readr::parse_number,na='nodata'))

标签: r

解决方案


假设 Excel 工作表的内容与此示例类似:

data.frame(
  col_1 = c(1, NA, 1), 
  col_2 = c("no data", 2, 2), 
  col_3 = c(NA, "no data", 3)) %>% 
  rio::export("db.xlsx") ## Exports the example.

db <- rio::import("db.xlsx") # Imports the example

db %>% 
  mutate(across(.cols = everything(), .fns = ~replace_na(data = .x, replace = ""))) %>% 
  na_if("no data") %>% 
  as_tibble() %>% # Optional
  mutate_all(as.numeric)

# A tibble: 3 x 3
  col_1 col_2 col_3
  <dbl> <dbl> <dbl>
1     1    NA    NA
2    NA     2    NA
3     1     2     3

推荐阅读