[R] List Conversion

Berwin A Turlach berwin at maths.uwa.edu.au
Thu Feb 9 04:35:53 CET 2006


>>>>> "LD" == Liz Dem <liz392 at mail.com> 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 6009                e-mail: berwin at maths.uwa.edu.au
Australia                        http://www.maths.uwa.edu.au/~berwin




More information about the R-help mailing list