简体   繁体   English

如何从R中列表的每个向量中选择项目

[英]How to select items from each vector of the list in R

I would like to select the third item from each vector of the list below. 我想从下面的列表的每个向量中选择第三项。 I tried in this way, but I got problems at level 2. I found the function select.list() but I do not know how to apply it. 我以这种方式尝试过,但是在2级时遇到了问题。我找到了select.list()函数,但我不知道如何应用它。 Any suggestions? 有什么建议么? Many thanks. 非常感谢。

newlist =  x[[1:140]][3]
List of 140
chr(0)
chr [1:7] Brachy leaf N11428394 1 
chr [1:7] Brachy leaf N10508942 141 
chr(0) 
chr [1:7] Brachy leaf N35663 5 
chr [1:7] Brachy leaf N12458414 1 
chr [1:7] Brachy leaf N5242558 16 
chr [1:7] Brachy leaf N7738408 1 
chr [1:10] Brachy leaf N9826491 633 

If I understand the code you show, and x is the list you want to select from , then this will work: 如果我理解您显示的代码,并且x是您要从中选择的列表,那么它将起作用:

lapply(x, FUN = `[`, 3)

Explanation: 说明:

lapply() takes each component of the supplied list and applies a function to it. lapply()接受提供的列表的每个组件,并对它应用一个函数。 In effect it is extracting x[[1]] and applying FUN to that, then extracting x[[2]] and applying FUN to it, and so on. 实际上,它是提取x[[1]]并对其应用FUN ,然后提取x[[2]]并对其应用FUN ,依此类推。 So that takes care of this part of your code: x[[1:140]] . 这样就可以处理代码的这一部分: x[[1:140]] You just need to do an extract of the 3 element as the FUN applied. 您只需在应用FUN时提取3个元素。 `[` is actually a function in R so we can use it as FUN . `[`实际上是R中的一个函数,因此我们可以将其用作FUN It has to be quoted as it is a special name. 由于它是一个特殊名称,因此必须引用它。 The final part is to supply arguments to `[`() , which we do here using a unnamed argument (the 3 in the function call shown). 最后一部分是为`[`()提供参数,我们在这里使用一个未命名的参数(显示的函数调用中的3 )进行此操作。

Example: 例:

> x <- list(A = letters[1:7], B = letters[1:7], C = letters[1:7])
> (newlist <- lapply(x, `[`, 3))
$A
[1] "c"

$B
[1] "c"

$C
[1] "c"

> 
> ## or as a vector (not a list) result
> (newlist2 <- sapply(x, `[`, 3))
  A   B   C 
"c" "c" "c"

Here is one way to do it 这是一种方法

x = list('Brachy leaf N11428394 1', 
        'Brachy leaf N10508942 141', 
        'Brachy leaf N356635')
sapply(sapply(x, strsplit, split = " "), '[', 3)

This gives 这给

[1] "N11428394" "N10508942" "N356635" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM