1

I have a vector v with row positions:

v<-c(10,3,100,50,...)

with those positions I want to extract elements of a list, having a column fixed, for example lets suppose my column number is 2, so I am doing:

data<-c()
data<-c(list1[[v]][[2]])

list1 has the data in the following format:

[[34]]
      [1] "200_s_at" "483"        "1933"        "3664"        

So for example, I want to extract from the row 342 the value 1910 only, column 2, and do the same with the next rows

but I got an error when I want to do that, is it possible to do it directly? or should I have a loop that read one by one the positions in v and fill the data vector like:

#algorithm
for i<-1 to length(v)
    pos<-v[i]
    data[[i]]<-c(list1[[pos]][[2]])
next i

Thanks

Layla
  • 5,234
  • 15
  • 51
  • 66

1 Answers1

7

You can use sapply as below:

sapply(list1[v], `[`, 2)

However, depending on your data, you might get an unexpected output, as explained in Why is `vapply` safer than `sapply`?. For example, what if some of your list items have length < 2? What if some of the list items are not vectors but data.frames? Also, the output class may differ based on the class of your list elements (logical, integer, numeric, character). If for example, you expect that all your list items are character vectors of length >= 2, then it is safer to do:

vapply(list1[v], `[`, character(1), 2)

where vapply will double check your assumptions for you, and error out if it finds a problem.

Community
  • 1
  • 1
flodel
  • 87,577
  • 21
  • 185
  • 223
  • list1 has the data and v has the positions, I dont see that you are using v at all – Layla Oct 14 '12 at 21:46
  • thanks @flodel, I forget to put another variable, by the way would you know how to get rid of the NA values that I got in the new vector? – Layla Oct 14 '12 at 22:05
  • Read this - http://stackoverflow.com/questions/7706876/r-script-removing-na-values-from-a-vector – flodel Oct 14 '12 at 22:12