【问题标题】:Is there a way to rbind files without it needing to convert from numeric to character in R?有没有一种方法可以 rbind 文件而不需要在 R 中从数字转换为字符?
【发布时间】:2019-11-18 14:08:53
【问题描述】:

我正在尝试使用以下代码读取 80 多个 .xlsx 格式的 excel 文件并将其合并到一个数据库中:

library(readxl)
library(purr)
library(dplyr)
library(tidyverse)

file.list <- list.files(pattern='*.xlsx')
alldata <- file.list %>%
map_dfr(read_excel) %>%
reduce(bind_rows)

我遇到的问题是Error: Column 'Cage' can't be converted from numeric to character。当我对其他列有这个问题时,我只需要从列中删除任何意外的非数字字符。但是,我不能为此列执行此操作,因为我有时需要列包含正斜杠。谁能帮我避免这个问题?

注意:无论我使用reduce(rbind_list)reduce(rbind.fill) 还是reduce(rbind),都会出现此错误

【问题讨论】:

  • 您应该考虑使用条件语句(例如 if() 与正则表达式匹配语句配对来识别斜杠是否存在 - 如果存在则修剪列名
  • 你能提供一个有问题的数据的最小例子吗?
  • 您可以在将所有单独的 excel 文件和相关列绑定在一起之前尝试为它们应用 as.character,从而确保它们的列类型匹配

标签: r type-conversion bind rbind


【解决方案1】:
library(readxl)
library(tidyverse)

alldata <- file.list %>%
     map_dfr(~read_excel(.x) %>% 
                mutate_all(as.character))

猜你可能已经完成了这个,但可以看到这个问题难倒其他人。您可以通过添加%&gt;% mutate_all(as.character) 来标准化read_excel 函数中的每一列来解决它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多