Передача Indedes в качестве аргументов в R - PullRequest
1 голос
/ 11 июня 2019

Я пытаюсь извлечь значения из большого числа списков, таких как приведенный ниже (который имеет тысячи записей первого уровня, как этот).Списки одинаковы по своей структуре первого уровня, но количество / форма извлекаемой информации зависит от уровня ниже.

library(tidyverse)

split_extract <- list(structure(c("1 Introduction ", "2 Intermediaries and technological innovation systems ", 
                                    "2.1 Intermediaries’ support for (eco)-innovation ", "2.2 Technological innovation systems (TIS) ", 
                                    "2.3 Linking functions thinking from TIS to intermediaries’ support roles ", 
                                    "3 The analytical approach ", "3.1 Step 1: defining the study focus ", 
                                    "3.2 Step 2: identify intermediaries in the context ", "3.3 Step 3: mapping roles of intermediaries ", 
                                    "3.4 Step 4: assessing the potential roles of intermediaries in eco-innovation ", 
                                    "3.5 Step 5: recommendations for intermediaries and their key stakeholders ", 
                                    "4 Example: analysing the potential roles of intermediaries to support eco-innovation in the region of Scania and North Rhine Westphalia ", 
                                    "4.1 Step 1 – define the study focus ", "4.2 Step 2 – identify intermediaries in the context ", 
                                    "4.3 Step 3 – map roles of the roles of intermediaries in eco-innovation ", 
                                    "4.4 Step 4 – assess the roles of intermediaries ", "5 Discussion ", 
                                    "6 Conclusions and further research ", NA, NA, ".1", ".2", ".3", 
                                    NA, ".1", ".2", ".3", ".4", ".5", NA, ".1", ".2", ".3", ".4", 
                                    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
                                    NA, NA, NA, NA, "Introduction ", "Intermediaries and technological innovation systems ", 
                                    "Intermediaries’ support for (eco)-innovation ", "Technological innovation systems (TIS) ", 
                                    "Linking functions thinking from TIS to intermediaries’ support roles ", 
                                    "The analytical approach ", "Step 1: defining the study focus ", 
                                    "Step 2: identify intermediaries in the context ", "Step 3: mapping roles of intermediaries ", 
                                    "Step 4: assessing the potential roles of intermediaries in eco-innovation ", 
                                    "Step 5: recommendations for intermediaries and their key stakeholders ", 
                                    "Example: analysing the potential roles of intermediaries to support eco-innovation in the region of Scania and North Rhine Westphalia ", 
                                    "Step 1 – define the study focus ", "Step 2 – identify intermediaries in the context ", 
                                    "Step 3 – map roles of the roles of intermediaries in eco-innovation ", 
                                    "Step 4 – assess the roles of intermediaries ", "Discussion ", 
                                    "Conclusions and further research ", NA, NA, NA, NA, NA, NA, 
                                    "Step", "Step", "Step", "Step", "Step", NA, "Step", "Step", "Step", 
                                    "Step", NA, NA), .Dim = c(18L, 5L)))

Я создал короткую функцию, к которой хотел быпередать index в качестве аргумента, либо в виде простого целого числа (например, 1), которое можно легко подключить, либо в виде строки в форме "i,j" для последующей оценки внутри вызова.Часто это может быть что-то вроде ",1", как в этом случае.

lext <- function(list, index) {

  if(typeof(index) == "character") {index <- rlang::parse_expr(index)}

  map(1:length(list), ~list[[.x]][rlang::eval_bare(index)])

}

l <- lext(split_extract, index = ",1")

Тем не менее, я получаю ошибку ниже, которая подсказывает мне, что маршрут синтаксического анализа, который я выбрал, является неправильным ... но яне знаю, как еще это сделать.

#> Error in parse(text = x): <text>:1:1: unexpected ','
#> 1: ,
#>     ^

Любая помощь будет высоко ценится!

Ответы [ 2 ]

2 голосов
/ 11 июня 2019

Использование ... работает с lapply, но не с purrr ...

lext <- function(list, ...) {
  lapply(seq_along(list), function(x) list[[x]][...])
}
lext(split_extracted, , 1)

Или просто

lext <- function(list, ...) {
  lapply(list, function(x) x[...])
}
1 голос
/ 11 июня 2019

Как насчет этого?

lext <- function(list, index) {
  if(typeof(index) == "character") {index <- rlang::parse_expr(sprintf(".x[%s]", index))}
  map(list, ~rlang::eval_bare(index))
}

l <- lext(split_extract, index = ",1")

[[1]]
 [1] "1 Introduction "                                                                                                                         
 [2] "2 Intermediaries and technological innovation systems "                                                                                  
 [3] "2.1 Intermediaries’ support for (eco)-innovation "                                                                                       
 [4] "2.2 Technological innovation systems (TIS) "                                                                                             
 [5] "2.3 Linking functions thinking from TIS to intermediaries’ support roles "                                                               
 [6] "3 The analytical approach "                                                                                                              
 [7] "3.1 Step 1: defining the study focus "                                                                                                   
 [8] "3.2 Step 2: identify intermediaries in the context "                                                                                     
 [9] "3.3 Step 3: mapping roles of intermediaries "                                                                                            
[10] "3.4 Step 4: assessing the potential roles of intermediaries in eco-innovation "                                                          
[11] "3.5 Step 5: recommendations for intermediaries and their key stakeholders "                                                              
[12] "4 Example: analysing the potential roles of intermediaries to support eco-innovation in the region of Scania and North Rhine Westphalia "
[13] "4.1 Step 1 – define the study focus "                                                                                                    
[14] "4.2 Step 2 – identify intermediaries in the context "                                                                                    
[15] "4.3 Step 3 – map roles of the roles of intermediaries in eco-innovation "                                                                
[16] "4.4 Step 4 – assess the roles of intermediaries "                                                                                        
[17] "5 Discussion "                                                                                                                           
[18] "6 Conclusions and further research "  

Еще один тест:

l <- lext(split_extract, index = "2,1")

[[1]]
[1] "2 Intermediaries and technological innovation systems "
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...