'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

"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
r


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jay.sf