Re: read CSV
- To: mathgroup at smc.vnet.net
- Subject: [mg117811] Re: read CSV
- From: annetts729 <annetts729 at gmail.com>
- Date: Thu, 31 Mar 2011 06:04:04 -0500 (EST)
- References: <imus7l$i3t$1@smc.vnet.net>
Hi Alan,
On Mar 30, 5:13 pm, Alan <alan.is... at gmail.com> wrote:
> I've received some files formatted like below.
> How can I read selected columns into a list?
> I'm coming from a background where I'd read in each line,
> discarding the first, then (in this case at least)
> split on the comma, and coerce the type. So I'm happy
> to do that if I can figure out how. (Naturally I could
> preprocess the data into a form that say ReadList
> likes better, but I'm looking for a pure Mathematica solution.)
>
> Thanks,
> Alan Isaac
>
> "x","y","color","pen down?"
> "0","0.26161459854014585","105","true"
> "1","0.2665251497682828","105","true"
> "2","0.29244385081680907","105","true"
> "3","0.31995416628471895","105","true"
Something like
irawd = Import["Isaac.txt", "Table"] (* read data *);
ihedr = irawd[[1]] (* header *);
idata = Rest@irawd (* siphon off from rest of data *);
idata = StringReplace[#, {"\"" -> "", "true" -> "True"}] & /@ idata
(* string processing *);
idata = StringSplit[#, ","] & /@ idata (* split line into strings *);
idata = Map[Flatten, idata, 1] (* and flatten appropriately *)
will read data in the file which is cut from your post.
Now we want to assign variables to columns. Use
xcord = ToExpression@idata[[All, 1]] ;
ycord = ToExpression@idata[[All, 2]];
or simply
cords = ToExpression@idata[[All, {1, 2}]];
colour = ToExpression@idata[[All, 3]];
pen = idata[[All, 4]];
which we can use like
rawg = If[pen[[#]],
{Directive[Hue[colour[[#]]/255], PointSize[.01]],
Point[cords[[#]]]},
{Directive[White], Point[cords[[#]]]}
] & /@ Range@Length@colour;
Show[Graphics@rawg, Frame -> True, AspectRatio -> .75]
D.