首页 > 解决方案 > 如何读取缩进的数据?

问题描述

我有一个制表符分隔的文件,如下所示:

ID  trait1  trait2  trait3
    1111    1   1   0
    2222    1   0   0
    3333    0   0   1
    4444    0   1   0

请注意,数据行相对于列标题缩进。

我尝试使用这种语法读取文件并保留列名:

df <- fread("/path/to/file", sep="\t", data.table=FALSE, header=TRUE)

结果如下所示:

df
  V1 1111 1 1 0
1 NA 2222 1 0 0
2 NA 3333 0 0 1
3 NA 4444 0 1 0

我试过strip.white = TRUE了,但这没有帮助。

标签: rdata.table

解决方案


read_table2readr也可以工作

readr::read_table2(
"ID  trait1  trait2  trait3
    1111    1   1   0
    2222    1   0   0
    3333    0   0   1
    4444    0   1   0
"
)
#> # A tibble: 4 x 4
#>      ID trait1 trait2 trait3
#>   <dbl>  <dbl>  <dbl>  <dbl>
#> 1  1111      1      1      0
#> 2  2222      1      0      0
#> 3  3333      0      0      1
#> 4  4444      0      1      0

reprex 包(v0.3.0)于 2019 年 9 月 17 日创建


推荐阅读