[R] Re ad in a file - produce independent vectors
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Jul 4 17:41:59 CEST 2008
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, ripley at stats.ox.ac.uk
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
More information about the R-help
mailing list