Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-使用列表中每个项目的第一个元素筛选列表_R_List_Subset_Purrr - Fatal编程技术网

R-使用列表中每个项目的第一个元素筛选列表

R-使用列表中每个项目的第一个元素筛选列表,r,list,subset,purrr,R,List,Subset,Purrr,我对R相当陌生,我正在尝试将数据从PDF解析到数据表中。我已经能够将文本解析到列表中,但是我很难从列表中筛选数据 作为例子,考虑下面的样本列表: l_vectors <- list( c("K", "10", "20"), c("1", "30", "40"), c("a", "b", "c"), c("x", "y", "z")) 从我听说的情况来看,我不太确定最好的方向。

我对R相当陌生,我正在尝试将数据从PDF解析到数据表中。我已经能够将文本解析到列表中,但是我很难从列表中筛选数据

作为例子,考虑下面的样本列表:

l_vectors <- list( c("K", "10", "20"),
                   c("1", "30", "40"),
                   c("a", "b", "c"),
                   c("x", "y", "z"))
从我听说的情况来看,我不太确定最好的方向。我猜我想把这个逻辑向量和Pulk结合起来使用,但似乎无法理解。任何帮助都将不胜感激

干杯,
Jonathon

一个选项是
keep
循环
向量
列表
,创建长度为1的逻辑向量,用
stru detect
包装
any
。这里检查的模式是字符串开头(
^
)的字符“K”或(
|
)“1”

library(purrr)
library(stringr)
keep(l_vectors, ~ any(str_detect(.x, "^(K|1)")))
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"
如果我们只检查第一个元素,则无需包装
任何

keep(l_vectors, ~ str_detect(.x[1], "^(K|1)"))
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"
如果它是一个固定匹配项,那么在@markus post中,可以使用%

keep(l_vectors,  ~ .x[1] %in% c("K", "1"))

如果您想使用baseR,可以编写一个helper函数,然后使用
Filter

f <- function(x) x[1] %in% c("K", "1")
Filter(f, l_vectors)
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"
f <- function(x) x[1] %in% c("K", "1")
Filter(f, l_vectors)
#[[1]]
#[1] "K"  "10" "20"

#[[2]]
#[1] "1"  "30" "40"
Filter(function(x) x[1] %in% c("K", "1"), l_vectors)