如何得到两个R命名列表之间的区别?

时间:2022-04-04 19:10:51

OK, I've got two named lists, one is "expected" and one is "observed". They may be complex in structure, with arbitrary data types. I want to get a new list containing just those elements of the observed list that are different from what's in the expected list. Here's an example:

我有两个命名列表,一个是“expect”,一个是“observed”。它们的结构可能很复杂,具有任意的数据类型。我想要得到一个新列表,其中只包含观察列表中与预期列表中不同的元素。这里有一个例子:

Lexp <- list(a=1, b="two", c=list(3, "four"))
Lobs <- list(a=1, c=list(3, "four"), b="ni")
Lwant <- list(b="ni")

Lwant is what I want the result to be. I tried this:

Lwant就是我想要的结果。我试着这样的:

> setdiff(Lobs, Lexp)
[[1]]
[1] "ni"

Nope, that loses the name, and I don't think setdiff pays attention to the names. Order clearly doesn't matter here, and I don't want a=1 to match with b=1.

不,这失去了名字,我不认为setdiff注意这些名字。顺序在这里显然不重要,我不希望a=1与b=1匹配。

Not sure what a good approach is... Something that loops over a list of names(Lobs)? Sounds clumsy and non-R-like, although workable... Got any elegant ideas?

不知道什么是好方法……什么东西循环遍历一个名字列表(lob)?听起来笨拙而不像rr,虽然可行……有优雅的想法吗?

2 个解决方案

#1


23  

At least in this case

至少在这种情况下

Lobs[!(Lobs %in% Lexp)]

lob(!(lob % % Lexp))

gives you what you want.

给你想要的。

#2


0  

OK, I found one slightly obtuse answer, using the plyr package:

好的,我找到了一个稍微有点迟钝的答案,使用plyr包:

> Lobs[laply(names(Lobs), function(x) !identical(Lobs[[x]], Lexp[[x]]))]
$b
[1] "ni"

So, it takes the names of the array from the observed function, uses double-bracket indexing and the identical() function to compare the sub-lists, then uses the binary array that results from laply() to index into the original observed function.

因此,它从观察到的函数中获取数组的名称,使用双括号索引和相同的()函数来比较子列表,然后使用laply()生成的二进制数组来索引到原始观察到的函数中。

Anyone got a better/cleaner/sexier/faster way?

有人有更好的/更干净的/更性感的/更快的方法吗?

#1


23  

At least in this case

至少在这种情况下

Lobs[!(Lobs %in% Lexp)]

lob(!(lob % % Lexp))

gives you what you want.

给你想要的。

#2


0  

OK, I found one slightly obtuse answer, using the plyr package:

好的,我找到了一个稍微有点迟钝的答案,使用plyr包:

> Lobs[laply(names(Lobs), function(x) !identical(Lobs[[x]], Lexp[[x]]))]
$b
[1] "ni"

So, it takes the names of the array from the observed function, uses double-bracket indexing and the identical() function to compare the sub-lists, then uses the binary array that results from laply() to index into the original observed function.

因此,它从观察到的函数中获取数组的名称,使用双括号索引和相同的()函数来比较子列表,然后使用laply()生成的二进制数组来索引到原始观察到的函数中。

Anyone got a better/cleaner/sexier/faster way?

有人有更好的/更干净的/更性感的/更快的方法吗?