[R] List Conversion

2006-02-08 Thread Liz Dem
Hello,

I have a list (mode and class are list) in R that is many elements long and of 
the form:
length(list)
[1] 5778
list[1:4]
$ID1
[1] num1
$ID2
[1] num2 num3
$ID3
[1] num4
$ID4
[1] NA

I'd like to convert the $ID2 value to be in one element rather than in two.  It 
shows up as c(\num2\, \num3\) if I try to use paste(list[2], collapse=).  
I need to do this over the length of the entire list, however list2 - 
apply(list, 1, paste, collapse=) tells me 'Error in apply : dim(X) must have 
a positive length'.  dim(list) does not have a positive length, which I think 
is due to the fact that it's a list and not a matrix or data frame.  

What I want to get is:
list[1:4]
$ID1
[1] num1
$ID2
[1] num2 num3
$ID3
[1] num4
$ID4
[1] NA

Thanks.
Liz

-- 
___
Play 100s of games for FREE! http://games.mail.com/

__
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html


Re: [R] List Conversion

2006-02-08 Thread Berwin A Turlach
 LD == Liz Dem [EMAIL PROTECTED] writes:

LD I have a list (mode and class are list) in R that is many elements long 
and of the form:
 length(list)
LD [1] 5778
 list[1:4]
LD $ID1
LD [1] num1
LD $ID2
LD [1] num2 num3
LD $ID3
LD [1] num4
LD $ID4
LD [1] NA

LD I'd like to convert the $ID2 value to be in one element rather
LD than in two.  It shows up as c(\num2\, \num3\) if I try to
LD use paste(list[2], collapse=).
You want list[[2]], not list[2]:

 tt - list(ID1=num1, ID2=c(num2, num3), ID3 = num4, ID4 =NA)
 tt
$ID1
[1] num1

$ID2
[1] num2 num3

$ID3
[1] num4

$ID4
[1] NA

 paste(tt[2], collapse=)
[1] c(\num2\, \num3\)
  paste(tt[[2]], collapse=)
[1] num2num3
  paste(tt[[2]], collapse= )
[1] num2 num3


LD I need to do this over the length of the entire list, however
LD list2 - apply(list, 1, paste, collapse=) tells me 'Error in
LD apply : dim(X) must have a positive length'.
You want to use `lapply' not `apply':
 tt1 - lapply(tt, paste, collapse= )
 tt1
$ID1
[1] num1

$ID2
[1] num2 num3

$ID3
[1] num4

$ID4
[1] NA

LD What I want to get is:
 list[1:4]
LD $ID1
LD [1] num1
LD $ID2
LD [1] num2 num3
LD $ID3
LD [1] num4
LD $ID4
LD [1] NA
In that case, if you don't want NA's to turn into strings:

 tt2 - lapply(tt, function(x) if(is.na(x[1])) NA else paste(x, collapse= ))
 tt2
$ID1
[1] num1

$ID2
[1] num2 num3

$ID3
[1] num4

$ID4
[1] NA

HTH.

Cheers,

Berwin

== Full address 
Berwin A Turlach  Tel.: +61 (8) 6488 3338 (secr)   
School of Mathematics and Statistics+61 (8) 6488 3383 (self)  
The University of Western Australia   FAX : +61 (8) 6488 1028
35 Stirling Highway   
Crawley WA 6009e-mail: [EMAIL PROTECTED]
Australiahttp://www.maths.uwa.edu.au/~berwin

__
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html