Skip to content

List Conversion

2 messages · Liz Dem, Berwin A Turlach

#
Hello,

I have a list (mode and class are list) in R that is many elements long and of the form:
[1] 5778
$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:
$ID1
[1] "num1"
$ID2
[1] "num2 num3"
$ID3
[1] "num4"
$ID4
[1] NA

Thanks.
Liz
#
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]:
$ID1
[1] "num1"

$ID2
[1] "num2" "num3"

$ID3
[1] "num4"

$ID4
[1] NA
[1] "c(\"num2\", \"num3\")"
[1] "num2num3"
[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':
$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:
$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 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin