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
$breakfast
[1] "bacon"   "eggs"    "sausage"

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

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


--
Brian D. Ripley,                  [EMAIL PROTECTED]
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to