[R] read.csv to read output of system()?

David Winsemius dwinsemius at comcast.net
Sat Dec 12 18:12:17 CET 2009


On Dec 12, 2009, at 12:01 PM, Marianne Promberger wrote:

> Thanks for both replies.
>
> Let me start by giving a better minimal example, although indeed the
> regex replacement is not my problem.
>
> system("echo \"var1,var2,var3\none,two,three\none,this is a  
> comment,with commas.,three\" > file.csv")
>
>> On 12/12/09 11:02, David Winsemius wrote:
>>>
>>> You need to figure out how to do multiple replacements unless it is
>>> only the first comma that you are targeting:
>>>
>>>> readLines(pipe("sed -e 's/,/;/' ~/file.csv"))
>>> [1] "one;two,three"
>
> Lovely. What I really need is read.csv and this works (with my "good
> enough for the existing data; will optimize later as needed" regex):

I didn't post  a read.csv versions thought the application was obvious.
>
> read.csv(pipe("sed -e 's/\\( [a-zA-Z]\\+\\),/\\1;/g' file.csv"))
>
> I can't understand that I didn't try this. I think what I tried was
> pipe( ... file.csv |") (with a Unix pipe symbol a the end)
>
> Thanks!
>
> Jon Baron <baron at psych.upenn.edu> 12-Dec-09 16:21:
>> gsub(readLines("file.csv"),",",";")
>
> Using gsub would be even neater, as it would really be self-contained
> in R.
>
> gsub("( [A-Za-z]+),","\\1;",readLines("file.csv"))

 > txt <- gsub("( [A-Za-z]+),","\\1;",readLines("file.csv"))
 > read.csv(textConnection(txt), header=TRUE)
   var1                           var2  var3
1  one                            two three
2  one this is a comment;with commas. three

>
> seems to work fine, but how to get this into a data frame?
>
> Marianne
>
> -- 
> Marianne Promberger PhD, King's College London
> http://promberger.info
> R version 2.10.0 (2009-10-26)
> Ubuntu 9.04

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list