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

From: Prof Brian Ripley <>
Date: Fri, 04 Jul 2008 16:41:59 +0100 (BST)

On Fri, 4 Jul 2008, 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?

There are very many ways.

Perhaps one of the simplest is to use readLines() to get a character vector of one element per line, then strsplit() to split the line on whatever the separator used is. E.g.

meals <- readLines("meals.txt")
m2 <- strsplit(meals, " +")
names(m2) <- sapply(m2, `[`, 1)
m3 <- lapply(m2, `[`, -1)
> m3

[1] "bacon" "eggs" "sausage"

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

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

Brian D. Ripley,        
Professor of Applied Statistics,
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________ mailing list
PLEASE do read the posting guide
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 04 Jul 2008 - 15:45:05 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 - 16:31:31 GMT.

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

list of date sections of archive