Search Index List Entry in R

Given a list of R, I would like to find the index of a given list entry. For example, for the record "36" I want my output to be "2" . Also, how can I execute such requests in parallel using lapply?

 > list $'1' [1] "7" "12" "26" "29" $'2' [1] "11" "36" $'3' [1] "20" "49" $'4' [1] "39" "41" 
+5
source share
2 answers

Here is a single line that allows (perhaps?) The possibility that more than one list item will contain the string for which you are looking for:

 ## Some example data ll <- list(1:4, 5:6, 7:12, 1:12) ll <- lapply(ll, as.character) which(sapply(ll, FUN=function(X) "12" %in% X)) # [1] 3 4 
+9
source

First you can turn your list into data.frame, which maps the values ​​to their corresponding index in the list:

 ll <- list(c("7", "12", "26", "29"), c("11", "36"), c("20", "49"), c("39", "41")) df <- data.frame(value = unlist(ll), index = rep(seq_along(ll), lapply(ll, length))) df # value index # 1 7 1 # 2 12 1 # 3 26 1 # 4 29 1 # 5 11 2 # 6 36 2 # 7 20 3 # 8 49 3 # 9 39 4 # 10 41 4 

Then write a function using match to find the index of the first occurrence of the given value:

 find.idx <- function(val)df$index[match(val, df$value)] 

You can call this function one value or many times since match vectorized:

 find.idx("36") # [1] 2 find.idx(c("36", "41", "99")) # [1] 2 4 NA 

Of course, you can also run it through lapply , especially if you plan to run it in parallel:

 lapply(c("36", "41", "99"), find.idx) # [[1]] # [1] 2 # # [[2]] # [1] 4 # # [[3]] # [1] NA 

There are many options to run this last bit in parallel. I would recommend you weigh your options by searching http://cran.r-project.org/web/views/HighPerformanceComputing.html .

+2
source

Source: https://habr.com/ru/post/912248/


All Articles