I have a large data file consisting of a single line of text. The format resembles
Cat 14 Dog 15 Horse 16
I'd eventually like to get it into a data.frame
(so in the above example, I'd have two variables, Animal
and Number
). The number of characters in each "line" is fixed.
Any suggestions?
Edit: Thanks for all the suggestions. They solved the problem exactly as I asked. Unfortunately after running it I learned that I have missing data. However, the number of characters is still fixed. The example then becomes
Cat 14 15 Horse 16
with each line containing 11 characters (including spaces), animals being the first 7 and numbers being the next four.
This revision has been posted as a new question: Importing one long line of data with spaces into R.
This solution takes full advantage of scan()
's what
argument, and seems simpler (to me) than any of the others:
x <- scan(file = textConnection("Cat 14 Dog 15 Horse 16"),
what = list(Animal=character(), Number=numeric()))
# Convert x (at this point a list) into a data.frame
as.data.frame(x)
# Animal Number
# 1 Cat 14
# 2 Dog 15
# 3 Horse 16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With