Skip to content

String to list and visa versa

7 messages · Tom McCallum, Peter Dalgaard, Vladimir Dergachev +1 more

#
Hi,

I need to collapse a list into a string and then reparse it back into the  
list.  Normally when I need to do this I simply use write.csv and  
read.csv, but I need to do this in memory within R rather than writing out  
to file.  Are there any bespoke commands that any knows of that does  
something like this or any tips for doing this that anyone can suggest?  I  
basically don't care upon the string representation, only that I can  
manipulate the list as a string and then reparse it back to a valid list  
object.

Many thanks for your help,

Tom
#
On Tuesday 14 November 2006 12:00 pm, Tom McCallum wrote:
#List -> string:

#
# Put whatever you want into collapse to separate list entries
#
paste(unlist(L), collapse=",")

#String->list
strsplit(S, ",")

                best

                   Vladimir Dergachev
#
This approach won't work in very many cases (but then nor will write.csv).

The safest way I know is to use serialize() and unserialize().  Next to 
that, deparse(control="all") and parse(text=) are quite good and give a 
human-readable character representation.

If fidelity is not the main issue, as.character and toString spring to 
mind.  unlist is recursive, and is not going to come close to being 
faithful for other than very simple lists. And what if ',' is a character 
in one of the list elements?
On Tue, 14 Nov 2006, Vladimir Dergachev wrote:

            
'a valid list object' or the original list object?

  
    
#
"Tom McCallum" <tom.mccallum at levelelimited.com> writes:
Er, perhaps you should send that sentence off to Iain McC.[*], so that
we can find out what killed it. ;-)
You might want to investigate deparse() and parse().

[*] http://www.johnhannah.net/mccallum.html
#
On Tuesday 14 November 2006 12:28 pm, Prof Brian Ripley wrote:
Yes, but then one can replace ',' with something rarely used like \007.
I picked ',' because write.csv/read.csv worked before.

You are right, for storage serialize/unserialize seem best, however for 
manipulation one would usually prefer a well-defined format.
 
                         best

                             Vladimir Dergachev
#
On Tue, 14 Nov 2006, Vladimir Dergachev wrote:

            
But it quotes strings ....

  
    
#
On Wed, 15 Nov 2006 05:00:28 -0000, Prof Brian Ripley
<ripley at stats.ox.ac.uk> wrote:

            
Thanks for the information, I think I am going to use the  
serialize/unserialize methods, which will mean I can't manipulate them  
outside R, but I can alter other parts of the project to accomodate this.

Tom