在列表的列中查找特定值 [英] Find specific value in a column of a list
问题描述
我试图获取列表的哪些对象在其列之一中具有特定值。
I'm trying to get which objects of a list have an specific value in one of their columns.
为了解释我的情况,请运行以下简单示例:
In order to explain my case, please run the following simple example:
mt_list = split(mtcars, f = mtcars$cyl)
如果我们查看其中一个元素,则会看到齿轮列。
head(mt_list$`4`)
mpg cyl disp hp drat wt qsec vs am gear carb
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
我想知道哪个元素ent的值为 4。在齿轮中柱。因此,它将搜索列表的所有元素,在齿轮列中。
What I'd like is to know which elements have a value of "4" in the "gear" column. So it will search into all elements of the list , inside the column "gear" and if is found a value of 5 then list the element.
所需的输出应为= 4,如果找到的值为5,则列出该元素。 6表示,您可以在其中找到值 4。在圆柱齿轮上。 (不在元素 8中显示)
The desired output should be = "4" "6" , where you can find the value "4" in the column gear. (not present in element "8")
任何帮助将不胜感激。
谢谢。
推荐答案
我们可以遍历列表
,检查是否有任何$ 齿轮列中的c $ c>元素等于4,使用它来对
列表中的
名称
进行子集
We could loop through the list
, check whether there is any
element in 'gear' column that is equal to 4, use that to subset the names
of the list
names(mt_list)[sapply(mt_list, function(x) any(x$gear == 4))]
#[1] "4" "6"
或使用%in%
创建逻辑索引
names(mt_list)[sapply(mt_list, function(x) 4 %in% x$gear)]
#[1] "4" "6"
这篇关于在列表的列中查找特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!