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

Marc Schwartz marc_schwartz at comcast.net
Fri Jul 4 17:36:52 CEST 2008


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



More information about the R-help mailing list