[R] where is a value in my list

David Winsemius dwinsemius at comcast.net
Sun Nov 15 16:24:41 CET 2009


On Nov 15, 2009, at 10:01 AM, Grzes wrote:

>
> I heve got a list:
>
> lista=list()
> a=c(2,4,5,5,6)
> b=c(3,5,4,2)
> c=c(1,1,1,8)
> lista[[1]]=a
> lista[[2]]=b
> lista[[3]]=c
>
>> lista
> [[1]]
> [1] 2 4 5 5 6
>
> [[2]]
> [1] 3 5 4 2
>
> [[3]]
> [1] 1 1 1 8
>
> I would like to know where is number 5 (which line)?
>
> For example I have got a loop:
>
>  k= vector(mode = "integer", length = 3)
>
> for(i in 1:3)
> {
> for (j in 1:length(lista[[i]])){
> if ((lista[[i]][j])==5   k[i]= [i])
> }
> }
>
> This loop is wrong but I would like to get in my vector k sth like  
> this:
>
> k = lista[[1]][1], lista[[2]][1]     ...or sth similar

I am a bit confused, since clearly lista[[1]][1] does _not_ == 5. It's  
also unclear what type of output you expect ... character, list,  
numeric?

See if these take you any further to your vaguely expressed goal:

 > lapply(lista, "%in%", 5)
[[1]]
[1] FALSE FALSE  TRUE  TRUE FALSE

[[2]]
[1] FALSE  TRUE FALSE FALSE

[[3]]
[1] FALSE FALSE FALSE FALSE

 > lapply(lista, function(x) which(x == 5) )
[[1]]
[1] 3 4

[[2]]
[1] 2

[[3]]
integer(0)

> --


David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list