Re: [R] List Conversion

From: Berwin A Turlach <berwin_at_maths.uwa.edu.au>
Date: Thu 09 Feb 2006 - 14:35:53 EST

>>>>> "LD" == Liz Dem <liz392@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


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 Received on Thu Feb 09 14:46:03 2006

This archive was generated by hypermail 2.1.8 : Fri 10 Feb 2006 - 23:01:53 EST