Re: [R] Subsetting a list

From: Martin Maechler <maechler_at_stat.math.ethz.ch>
Date: Thu 20 Oct 2005 - 01:09:01 EST

>>>>> "Jose" == Josť Ernesto Jardim <ernesto@ipimar.pt> >>>>> on Tue, 18 Oct 2005 15:30:59 +0100 writes:

    Jose> Dennis Fisher wrote:
>> Colleagues,
>>
>> I have created a list in the following manner:
>> TEST <- list(c("A1", "A2"), c("B1", "B2"), c("C1", "C2"))
>>
>> I now want to delete one element from the list, e.g., the third. The
>> command
>> TEST[[3]]
>> yields (as expected):
>> [1] "C1" "C2"
>>
>> The command
>> TEST[[-3]]
>> yields:
>> Error: attempt to select more than one element
>>
>> How can I accomplish delete one or more elements from this list?
>>
>> I am running R2.2.0 on a Linux platform.
>>
>> Dennis
>>

    Jose> TEST[[3]] <- NULL

    Jose> Lists are not subsetable like data.frames or arrays, see the manuals.

yes, they are, almost, see other replies and "the manuals" :

Lists can have 'dim' attributes and hence be treated as arrays; Note that this is pretty rarely used and not too well supported by some tools, one could say even 'print()' :

> set.seed(0); L0 <- L <- lapply(rpois(12, lambda=3), seq); dim(L) <- 3:4; L

     [,1] [,2] [,3] [,4]

[1,] Integer,5 Integer,3 Integer,5 Integer,3
[2,] Integer,2 Integer,5 Integer,6 1        
[3,] Integer,2 Integer,2 Integer,4 Integer,2
> str(L)
List of 12
 $ : int [1:5] 1 2 3 4 5
 $ : int [1:2] 1 2
 $ : int [1:2] 1 2
 $ : int [1:3] 1 2 3
 $ : int [1:5] 1 2 3 4 5
 $ : int [1:2] 1 2
 $ : int [1:5] 1 2 3 4 5
 $ : int [1:6] 1 2 3 4 5 6
 $ : int [1:4] 1 2 3 4
 $ : int [1:3] 1 2 3
 $ : int 1
 $ : int [1:2] 1 2

> L[-(1:10)] ## treated matrix ``as vector'' [[1]]
[1] 1

[[2]]
[1] 1 2



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 Oct 20 01:23:54 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:40:46 EST