我试图解决使用readxl包将xls数据导入R的问题。特定的xls文件有18列和472行,前7行有需要跳过的描述性文本。我只想从EDA的18列中选择1,3,6:9。它们具有混合类型,包括日期、数字和文本。
readxl似乎无法直接导入非连续列。我的计划是使用skip =7先读取整个工作表,然后使用select next步骤。但是,默认情况下,问题是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"))
发布于 2017-10-01 00:19:08
据我所知,您是,而不是,无法按列名指定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-17 17:03:42
所以我认为你可以:
read_excel(xlsx_example, col_types=col (Sepal.Length = col_numeric()))
https://stackoverflow.com/questions/46508029
复制相似问题