This question is a followup to my previous question, Importing one long line of data into R.
I have a large data file consisting of a single line of text. The format resembles
Cat 14 15 Horse 16
I’d eventually like to get it into a data.frame. In the above example I would end up with two variables, two variables, Animal and Number. The number of characters in each “line” is fixed, so in the example above each line contains 11 characters, animals being the first 7 and numbers being the next four.
So what I’d like is a data frame that looks like:
Animal Number
Cat 14
NA 15
Horse 16
You can read the file with
read.fwf, specifying the column widths and the number of columns:Here the argument
times = 3works for your sample data; for your real file, you’ll have to indicate how many pairs there are and changetimesaccordingly. If you don’t know how many entries you have, this might work:This will give you a data.frame with one row and many columns. You need to break that into many rows and two columns:
This will get you the correct shape for your data. The animal names are stored as character vectors, which you’ll probably want to change into factors, but at this point all the data is in R, so you can easily tweak it.