sam
sam

Reputation: 37

How can I read txt file into a dataframe and separate some of its content elsewhere?

The .txt file I have is like:

enter image description here

I want to load the table as a dataframe and want to save the variable info for reference. How can I do this?

Here is the link to the data: https://www.sao.ru/lv/lvgdb/article/suites_dw_Table1.txt

Upvotes: 0

Views: 48

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173858

You can read the file with readLines, find the line with the "--------" in it, then extract the line before and all lines after this. Feed the result to read.table

txt <- readLines("https://www.sao.ru/lv/lvgdb/article/suites_dw_Table1.txt")

underline <- grep("--------", txt)

df <- read.table(text = txt[c(underline - 1, (underline + 1):length(txt))], 
                 sep = "|", header = TRUE)

dplyr::tibble(df)
#> # A tibble: 796 x 12
#>    name        a_26   m_b log_lk log_m26 log_mhi   vlg   ti1 md        D delta~1
#>    <chr>      <dbl> <dbl>  <dbl>   <dbl> <chr>   <dbl> <dbl> <chr> <dbl>   <dbl>
#>  1 " HolmIX ~  2.96 -13.6   7.7     8.53 "  8.4~   192   5.1 " ME~  3.61      88
#>  2 " ClumpI ~  0.2   -8.3   5.57   NA    "     ~   -25   4.2 " ME~  3.6     -129
#>  3 " KDG061 ~  1.55 -12.9   8.09   NA    "     ~   360   4   " ME~  3.6      256
#>  4 " [CKT200~  0.88 -10.1   6.29   NA    "     ~   -46   4   " ME~  3.6     -150
#>  5 " ClumpII~  0.11  -8.3   5.57   NA    "     ~    19   3.9 " ME~  3.6      -85
#>  6 " NGC2976~  6.17 -17.1   9.42    9.15 "  8.0~   142   2.9 " ME~  3.56      38
#>  7 " MESSIER~ 13.2  -19.6  10.6     9.86 "  8.9~   328   2.8 " ME~  3.53     224
#>  8 " KDG064 ~  2.19 -12.6   7.98   NA    "     ~   121   2.7 " ME~  3.7       17
#>  9 " [CKT200~  0.87  -9.6   6.8    NA    "     ~    NA   2.5 " ME~  3.66      NA
#> 10 " IKN    ~  3.15 -11.6   7.6    NA    " <6.2~    -1   2.5 " ME~  3.75    -105
#> # ... with 786 more rows, 1 more variable: count <int>, and abbreviated
#> #   variable name 1: delta_vlg

Created on 2022-09-22 with reprex v2.0.2

Upvotes: 2

Related Questions