Re: [R] Re ad in a file - produce independent vectors

From: Marc Schwartz <>
Date: Fri, 04 Jul 2008 10:36:52 -0500

on 07/04/2008 09:38 AM jimineep wrote:
> Is there a way of reading in a file in a way that each line becomes a vector:
> for example:
> meals.txt
> breakfast bacon eggs sausage
> lunch sandwich apple marsbar crisps
> dinner chicken rice custard pie
> I want to read in this file and end up with 3 different vectors, one called
> breakfast which contains "bacon", "eggs", sausage" One called lunch with
> "sandwich", "apple"... etc
> So is there a way to do this with a file like this?
> Or would I need to transpose the file using something like Perl? And since
> the vectors are not all of equal length, would I have to also increase the
> size of the shorter lines by adding NAs? I'm working with a file much bigger
> than this and this could be a bit of a bother...
> Kind Regards,
> Jim

First, read in the data file using:

Lines <- readLines("meals.txt")

That gives you:

 > Lines

[1] "breakfast    bacon    eggs    sausage"
[2] "lunch    sandwich    apple    marsbar    crisps"
[3] "dinner    chicken    rice    custard    pie"

Note the current object list:

 > ls()
[1] "DF" "Lines"

# Now loop over each line, split it
# then take the first value and use assign()
# to create a vector with that name, containing
# the remaining elements

for (i in seq(along = Lines)) {

   Vec <- unlist(strsplit(Lines[i], " +"))    assign(Vec[1], Vec[-1])

Note the current object list:

 > ls()

[1] "breakfast" "DF"        "dinner"    "i"         "Lines"
[6] "lunch"     "Vec"

 > breakfast
[1] "bacon" "eggs" "sausage"

 > lunch
[1] "sandwich" "apple" "marsbar" "crisps"

 > dinner
[1] "chicken" "rice" "custard" "pie"

HTH, Marc Schwartz mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Fri 04 Jul 2008 - 15:40:24 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 04 Jul 2008 - 18:32:02 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive