2

我正在尝试使用readxl包解决将 xls 数据导入 R 的问题。具体的 xls 文件有 18 列和 472 行,前 7 行有需要跳过的描述性文本。我只想从 EDA 的 18 列中选择col 1,3,6:9。它们具有混合类型,包括日期、数字和文本。

readxl 似乎无法直接导入非连续列。我的计划是先使用 skip =7 阅读整张纸,然后使用 select next step。但是,问题是readxl默认将日期类型猜测为数字。readxl 有没有办法按列名指定col_types ?

带有示例 xlsx 的可重现代码,用于解决演示。

    library(readxl)

    xlsx_example <- readxl_example("datasets.xlsx")

    # read the entire table
    read_excel(xlsx_example)

    # select specific column to name - following code does not work

    read_excel(xlsx_example, col_types=col (Sepal.Length = "numeric"))
4

2 回答 2

2

据我所知,您无法col_types按列名指定。不过,可以只读取特定列。例如,

read_excel(xlsx_example, col_types=c("numeric", "skip", "numeric", "numeric", "skip"))

将导入第 1、3 和 4 列并跳过第 2 和 5 列。您可以对 18 列执行此操作,但我认为这有点难以跟踪哪个列被导入为哪种类型。

另一种方法是将所有列作为文本读取,col_types = "text"然后按名称选择和转换变量。例如:

library(tidyverse)
library(readxl)
xlsx_example <- readxl_example("datasets.xlsx")
df <- read_excel(xlsx_example, col_types = "text")
df %>% 
  select(Sepal.Length, Petal.Length) %>% 
  mutate(Sepal.Length = as.numeric(Sepal.Length))
#> # A tibble: 150 x 2
#>    Sepal.Length Petal.Length
#>           <dbl>        <chr>
#>  1          5.1          1.4
#>  2          4.9          1.4
#>  3          4.7          1.3
#>  4          4.6          1.5
#>  5          5.0          1.4
#>  6          5.4          1.7
#>  7          4.6          1.4
#>  8          5.0          1.5
#>  9          4.4          1.4
#> 10          4.9          1.5
#> # ... with 140 more rows
于 2017-10-01T00:19:08.883 回答
-2

所以我认为你可以这样做:

read_excel(xlsx_example, col_types=col (Sepal.Length = col_numeric()))
于 2017-10-17T17:03:42.943 回答