我有一个包含15000条记录的excel文件(.xlsx),我将它加载到R中,并且有一个'X‘列,它的数据在10000行之后。
Data <- read_excel("Business_Data.xlsx", sheet = 3, skip = 2)
当我在导入文件后检查数据帧时,我只能看到'X‘列中的NA。相反,列X有像“成本+,转售-,购买”这样的因素,这些因素没有被捕获。是不是因为该列的数据包含了10000条记录之后?还是我错过了什么?
发布于 2020-07-06 18:30:17
默认情况下,read_excel
尝试使用前1000行来推断数据的类型。如果它不能获得正确的类型,并且不能将数据强制转换为这种类型,那么您将得到NA。
您可能收到警告:“有50个或更多的警告(使用warnings()查看前50个)”。
检查警告会告诉你一些类似的东西:
> warnings()
Messages d'avis :
1: In read_fun(path = enc2native(normalizePath(path)), sheet_i = sheet, ... :
Expecting logical in B15002 / R15002C2: got 'A'
...
解决方案:添加参数guess_max = 20000
library(tidyverse)
library(writexl)
library(readxl)
# create a dataframe with a character column "empty" at the beginning
df1 <- tibble(x = 1:20000,
y = c(rep(NA_character_, 15000), rep("A", 5000)))
# bottom rows are OK
tail(df1)
#> # A tibble: 6 x 2
#> x y
#> <int> <chr>
#> 1 19995 A
#> 2 19996 A
#> 3 19997 A
#> 4 19998 A
#> 5 19999 A
#> 6 20000 A
write_xlsx(df1, "d:/temp/test.xlsx")
# we read back ; bottom rows are missing !
df2 <- read_xlsx("d:/temp/test.xlsx")
tail(df2)
#> # A tibble: 6 x 2
#> x y
#> <dbl> <lgl>
#> 1 19995 NA
#> 2 19996 NA
#> 3 19997 NA
#> 4 19998 NA
#> 5 19999 NA
#> 6 20000 NA
# everything is fine with guess_max = 20000
df3 <- read_xlsx("d:/temp/test.xlsx", guess_max = 20000)
tail(df3)
#> # A tibble: 6 x 2
#> x y
#> <dbl> <chr>
#> 1 19995 A
#> 2 19996 A
#> 3 19997 A
#> 4 19998 A
#> 5 19999 A
#> 6 20000 A
所以,检查警告!
要确保您也可以强制键入:
df4 <- read_xlsx("d:/temp/test.xlsx",
col_types = c("numeric", "text"))
请注意,在任何情况下,xlsx格式都无法识别整数,因此您可能需要将数字转换为整数,以获得准确的原始数据帧:
df4 %>%
mutate(x = as.integer(x)) %>%
identical(df1)
#> [1] TRUE
https://stackoverflow.com/questions/62751649
复制相似问题