【问题标题】:Create a Dataframe import several sheets in R在 R 中创建数据框导入多张工作表
【发布时间】:2020-03-28 20:33:53
【问题描述】:

我有三个 excel 文件,每个文件有 12 张。我想创建一个数据框,将三个文件的所有工作表与带有工作表编号的列连接起来。到目前为止,我有以下代码:

path <- 'PRT 2017.xlsx' #Just one file
sheets <- excel_sheets(path)
df2017 <- map_df(sheets,~ read_excel(path, sheet = .x), .id = "sheet")

但它会产生以下错误:

错误:列 ZZn 无法从字符转换为数字 Además:有 50 个或更多警告(使用 warnings() 查看前 50 个)

工作表的结构(工作表名称:201701)是:

FF                          ZN   ZZn     Q  
28/01/2017 09:07:32 a.m.   612   61201   4
12/01/2017 06:49:01 a.m.   728   DFT     10 

我想要的结果是:

FF                          ZN   ZZn     Q   Sheet
28/01/2017 09:07:32 a.m.   612   61201   4   201701
12/01/2017 06:49:01 a.m.   728   DFT     10  201701
28/02/2018 04:21:34 p.m.   405   40502   20  201802

谢谢...

【问题讨论】:

  • 这行得通吗? df2017 &lt;- map_df(sheets, read_excel(path, sheet = .x), .id = "sheet")。您在这里并没有真正使用公式。

标签: r dataframe rbind


【解决方案1】:

问题似乎是对于某些工作表ZZn 仅包含数值,而对于其他工作表还包含字符。因此,对于某些工作表,ZZn 是一个数字向量,而对于其他工作表,它是一个字符向量。但是,在这种情况下,将 df 绑定在一起不起作用。这就是错误消息告诉您的内容。

作为一个例子,看看这个:

library(dplyr)
library(purrr)

sheets <- list(
  a = data.frame(
    ZN = c(1, 2),
    ZZn = c(61201, "DFT"),
    stringsAsFactors = FALSE
  ),
  b = data.frame(
    ZN = c(3, 4),
    ZZn = c(61201, 61202),
    stringsAsFactors = FALSE
  )
)

# Error
map_df(sheets, ~ .x, .id = "sheet")
#> Error: Column `ZZn` can't be converted from character to numeric

# Works
map_df(sheets, ~ mutate(.x, ZZn = as.character(ZZn)), .id = "sheet")
#>   sheet ZN   ZZn
#> 1     a  1 61201
#> 2     a  2   DFT
#> 3     b  3 61201
#> 4     b  4 61202

reprex package (v0.3.0) 于 2020 年 3 月 29 日创建

因此,您必须在将工作表绑定在一起之前将数字向量转换为字符,就像这样

map_df(sheets, ~ read_excel(path, sheet = .x) %>% 
  mutate(ZZn = as.character(ZZn)), .id = "sheet")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多