How do I read text not in the a table like format?

r

Solution

Use scan in its multiline mode (for very regular groups of three items separated by a blank line):

filename="myPath/myFile.txt"
inp <- scan(filename, , what=as.list(rep("",3) ))
dinp <- as.data.frame(inp, stringsAsFactors=FALSE)
names(dinp) <- dinp[1,]  # use first set as the column names
dinp <- dinp[-1,]        # then remove from the data

Second attempt (different question)

dat <- readLines(filename)
# Matrices are column-major order, hence the t(). I suppose I could have used byrow=TRUE.
mydf <- as.data.frame( t(matrix(dat, nrow=5) )[-1,-5] )
names(mydf) <- dat[1:4]

#-----------------------------
> mydf
               Name   Type     Color                              About
1         Spiderman Marvel       Red                   Swings from webs
2          Superman     DC                          Likes to fly around
3             Hulk  Marvel     Green  I told you not top make him mad. 
4            Batman            Black He is a good fighter and detective
5 Martian Manhunter     DC                              He is from Mars
6          Deadpool        Black Red                        Kinda Crazy

Problem

How do I read a file in to R that is not in a table like format? The data has blank data for some values. The blanks need to be value. "About," and "Name," are the only values that will always be present. For example a text file as follows: ``` Name Type Color About Spiderman Marvel Red Swings from webs Superman DC Likes to fly around Hulk Marvel Green I told you not top make him mad. Batman Black He is a good fighter and detective Martian Manhunter DC He is from Mars Deadpool Black Red Kinda Crazy ``` The first entry being the headers. I want to turn it into a data frame like ``` Name Type Color About Spiderman Marvel Red Swings from webs Superman DC Likes to fly around Hulk Marvel Green I told you not top make him mad. Batman Black He is a good fighter and detective Mar...ter DC He is from Mars Deadpool Black Red Kinda Crazy ```

Original source