我有三个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
谢谢...
答案 0 :(得分:0)
问题似乎是,对于某些工作表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-03-29创建
因此,在将工作表绑定在一起之前,必须将数字矢量转换为字符,就像这样
map_df(sheets, ~ read_excel(path, sheet = .x) %>%
mutate(ZZn = as.character(ZZn)), .id = "sheet")