如何在 R 中查找变量的索引并对列表进行子集操作?

3

我有一个类似这样的列表

#Make dataframes
df1 = data.frame(x = c("a", "b", "c"), y = 1:3, stringsAsFactors = F)
df2 = df1 %>% mutate(y = y*2)
df3 = df1 %>% mutate(y = y*3)

#Make a name for each dataframe
myvar = "fname"

#Combine name and dataframe into a list
mylist = list(myvar, df1)

#Add the other dataframes and name to the list (done in a loop for my bigger dataset
list2 = list(myvar, df2)
mylist = rbind(mylist, list2)

list3  = list(myvar, df3)
mylist = rbind(mylist, list3)

我希望能够提取列表中与 "c" 相关的所有数据的子集。

  x y
3 c 3
  x y
3 c 6
  x y
3 c 9

这是我尝试的方法,但它并没有起作用

#Find all instances of "c"
picksite = "c"

site_indices = which(mylist[,2] == picksite)
mylist[site_indices,]

有什么建议可以做到这一点,甚至可以提供更好地理解列表的链接吗?非常感谢。

2个回答

2

lapply内部包装which即可解决此问题:

lapply(mylist[,2], FUN = function(i) i[which(i$x == "c"),])
$mylist
  x y
3 c 3

$list2
  x y
3 c 6

$list3
  x y
3 c 9

0
使用 tidyverse,我们可以使用 map 循环遍历 list 并使用 if_any 进行 filter
library(dplyr)
library(purrr)
map(mylist[,2], ~ .x %>%
    filter(if_any(everything(), ~ .x == "c")))

-输出

$mylist
  x y
1 c 3

$list2
  x y
1 c 6

$list3
  x y
1 c 9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接