read_delim 用于具有不同列数的多个文件

标签 r dplyr tidy

我正在尝试使用 read_delim 读取多个文本文件。但是,这些文本文件的不同之处在于它们具有多少列。我只对所有文本文件中常见的一些列感兴趣。

但是,当我尝试使用 col_select 指定列时,它仍然会抛出列数不同的错误。这是一个最小的例子:

> df = read_delim(c('file1.txt', 'file2.txt'), col_select = 1)
Error: Files must all have 3 columns:
* File 2 has 2 columns

但是,这有效并且只能在第一列中读取:

> df = read_delim('file1.txt', col_select = 1)
New names:                                                                                                                                                          
• `test2` -> `test2...2`
• `test2` -> `test2...3`
Rows: 1 Columns: 1
── Column specification ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Delimiter: "\t"
dbl (1): test1

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

file1.txt的内容:

test1 test2 test3
1 2 3

file2.txt的内容:

test1 test2
1 2

有人知道如何读取列数不同的文本文件吗?

最佳答案

由于它似乎检查列数是否相等,并且在列选择发生之前会出错,因此您可能需要单独读取每个列并绑定(bind)它们:

library(readr)
library(purrr)

set_names(c('file1.txt', 'file2.txt')) %>%
  map(read_delim, col_select = 1, show_col_types = FALSE) %>%
  list_rbind(names_to = "file_id")

# A tibble: 2 × 2
  file_id   test1
  <chr>     <dbl>
1 file1.txt     1
2 file2.txt     1

关于read_delim 用于具有不同列数的多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75246433/

相关文章:

r - 通过匹配列和值 R 对数据帧进行子集和分组

r - 用于计算 Cohen 的 f2 效应大小的 R 代码(对于多级模型)

r - gls 模型的 `emmeans` 没有 't run inside ` map `

php 整洁的奇怪行为

r - 在R中显示UTF-8编码的汉字

r - ggplot 图例中缺少彩条,Windows 远程桌面

r - 使用此列中的数据时排除 `dplyr` `mutate_at` 中的列

r - 使用 dplyr/tidyverse 进行类似扫描的操作

javascript - 用 ckeditor 整理 html

php - 整洁地用一个奇怪的字符替换