Skip to content

where is a value in my list

6 messages · Grzes, David Winsemius

#
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
#
On Nov 15, 2009, at 10:01 AM, Grzes wrote:

            
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
#
But it's not what I wont

I need get a number of line my list
5 is in: list[[1]][1] and list[[2]][1] so
I would like to get a vector k = 1,2
David Winsemius wrote:

  
    
#
On Nov 15, 2009, at 10:47 AM, Grzes wrote:

            
I am sorry. I do not understand what you want the second solution  
offered gave you numbers (and they were the numbers that were for  
"5"'s rather than one that were not for "5"'s as your offered solution.

If you just want to know which lists contain a 5, but not the position  
within the list (which was not what you appeared to be asking..):

 > which(sapply(lista, function(x) any(x == 5)))
[1] 1 2
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
#
It's excellent! 
Now, if I have a vector k=c( TRUE, TRUE, FALSE) how I may get lines from
list?
which (list ?? k) ?
David Winsemius wrote:

  
    
#
The term "line" in R refers to a sequence of text ending in and  
<EOL> marker, which I doubt is what you meant. Please stop referring  
to the items or elements of a list as "lines" if you hope to  
communicate with R-users.

 > lista[1:2]
[[1]]
[1] 2 4 5 5 6

[[2]]
[1] 3 5 4 2

 > lista[ which(sapply(lista, function(x) any(x == 5))) ]
[[1]]
[1] 2 4 5 5 6

[[2]]
[1] 3 5 4 2