Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing one long line of data into R

Tags:

r

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.

like image 924
user1082072 Avatar asked Dec 05 '11 18:12

user1082072


1 Answers

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
like image 180
Josh O'Brien Avatar answered Oct 19 '22 22:10

Josh O'Brien