Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read indented data?

Tags:

r

data.table

I have a tab-separated file that looks like this:

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

Notice the datalines are indented relative to the column headers.

I tried this syntax to read in the file and keep the column names:

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

The result looks like this:

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

I've tried strip.white = TRUE but this didn't help.

like image 603
TJ87 Avatar asked Feb 19 '26 00:02

TJ87


1 Answers

read_table2 from readr can also work

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

Created on 2019-09-17 by the reprex package (v0.3.0)

like image 182
Calum You Avatar answered Feb 20 '26 15:02

Calum You



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!