Debjyoti
Debjyoti

Reputation: 177

Store specific elements from a list into a chosen vector in R

My data: List of characters: https://i.sstatic.net/DUS2r.jpg enter image description here

I want to store specific elements(eg "h","k") from each of the above subsets within the list m into separate vectors Currently using the following code:

for (i in m[[1]][[1]]{if(i=="k"){t<-m[[1]][[1]][m[[1]][[1]]==i]}}

I can store specific elements in vector for 1 subset individually. I want to store elements from all subsets simultaneously. Thanks

Upvotes: 0

Views: 62

Answers (1)

Adelmo Filho
Adelmo Filho

Reputation: 396

First Of All, let's replicate your data!

a <- list(c("g", "g", "h", "k", "k", "k", "l"))
b <- list(c("g", "h", "k", "k", "k", "l", "g"))
c <- list(c("g", "h", "h", "h", "k", "l", "h"))

m <- append(append(list(a), list(b)), list(c))

> m
[[1]]
[[1]][[1]]
[1] "g" "g" "h" "k" "k" "k" "l"


[[2]]
[[2]][[1]]
[1] "g" "h" "k" "k" "k" "l" "g"


[[3]]
[[3]][[1]]
[1] "g" "h" "h" "h" "k" "l" "h"

Now, to store the specified element from all subsets simultaneously, we can add one more loop on your code:

t <- list()

for (j in 1:length(m)) {


  for (i in m[[j]][[1]]){

    if(i == "k"){

      t[[j]]<-m[[j]][[1]][m[[j]][[1]]==i]

      }

  }

}

On above case, we select the "k" element and response was:

> t
[[1]]
[1] "k" "k" "k"

[[2]]
[1] "k" "k" "k"

[[3]]
[1] "k"

Upvotes: 2

Related Questions