Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert txt file to dataframe in R

is there a way to convert txt file data into Dataframe in R

For example,
I have a df.txt file in my project folder

df.csv

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"a" "e" "b" "c" "d" "f"
a 1 e 1 b1 c1 d1 f1
"a" "e" "b" "c" "d" "f"
a1 e1 sdf c1 d1 f1
"a" "e" "b" "c" "d" "f"
a1 e1 sdf sdf d1 f1
"a" "e" "b" "c" "d" "f" "z"
a2 e1 b1 c1 d1 f1 z1

expected output

    a    e    b    c    d    f    z   ### column names

    a 1  e 1  b1   c1   d1   f1   NA
    a1   e1   sdf  c1   d1   f1   NA
    a1   e1   sdf  sdf  d1   f1   NA
    a2   e1   b1   c1   d1   f1   z1

>Solution :

You could do something like this.

z <- gsub('\"', '', readLines('df.csv', 8))
z <- strsplit(z, ' ')
z <- lapply(z, `length<-`, max(lengths(z)))

Map(\(x, y) setNames(x, y), 
    z[seq_along(z) %% 2 == 0],
    z[length(z) - 1]
    ) |> do.call(what='rbind') |> as.data.frame()

#    a  e   b   c  d  f    z
# 1 a1 e1  b1  c1 d1 f1 <NA>
# 2 a1 e1 sdf  c1 d1 f1 <NA>
# 3 a1 e1 sdf sdf d1 f1 <NA>
# 4 a2 e1  b1  c1 d1 f1   z1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading