我有一个没有标题行的大型 CSV 文件,并且标题可以作为向量提供给我。我想使用文件列的子集而不加载整个文件。所需列的子集作为单独的列表提供。
1,2,3,4
5,6,7,8
9,10,11,12
header <- c("A", "B", "C", "D")
subset <- c("D", "B")
到目前为止,我一直通过以下方式读取数据,这得到了我想要的结果,但首先加载整个文件。
# Setup
library(readr)
write.table(
structure(list(V1 = c(1L, 5L, 9L), V2 = c(2L, 6L, 10L), V3 = c(3L, 7L, 11L), V4 = c(4L, 8L, 12L)), class = "data.frame", row.names = c(NA, -3L)),
file="sample-data.csv",
row.names=FALSE,
col.names=FALSE,
sep=","
)
header <- c("A", "B", "C", "D")
subset <- c("D", "B")
# Current approach
df1 <- read_csv(
"sample-data.csv",
col_names = header
)[subset]
df1
# A tibble: 3 × 2
D B
<dbl> <dbl>
1 4 2
2 8 6
3 12 10
如何在不先加载整个文件的情况下获得相同的结果?
相关问题
read.table
和scan
之间的折衷方案?)[重复]未指定文件外的列名称,答案不适用于这种情况。您不必立即读取整个文件,因为
read_csv()
函数有一个参数。您只需将代码修改为
df1 <- read_csv(
"sample-data.csv",
col_names=c("D","B"),
col_select=c("D","B")
)
如果文件实际上不包含标题,那么您可以在
col_select
中调用列索引
df1 <- read_csv(
"sample-data.csv",
col_names=c("D","B"),
col_select=c(4,2)
)
如果您使用
read_csv
包中的 readr
,您将拥有参数 col_select
,您可以在其中选择要读取的列。
readr::read_csv()
函数有一个名为 col_select
的参数,它允许您使用与 dplyr::select()
相同的语言指定要读取的列。所以在实践中,这看起来像:
df1 <- readr::read_csv(
file = "sample-data.csv",
col_names = header,
col_select = c(D, B)
)
然后给出所需的输出:
# A tibble: 3 × 2
D B
<dbl> <dbl>
1 4 2
2 8 6
3 12 10
您还可以调用
attr(df1, "spec")
,确认读取文件时跳过列 A
和 C
。
header <- c("A", "B", "C", "D")
subset <- c("D", "B")
readr::read_csv("sample_data.csv",
col_names = header,
col_select = any_of(subset))
# A tibble: 3 × 2
D B
<dbl> <dbl>
1 4 2
2 8 6
3 12 10