[英]Delete individual matrices from a list dependent upon the result of a function on each matrix - in r
I have a list of matrices - list1. 我有一个矩阵列表-list1。 These matrices are named x1, x2, x3..... x999, x1000. 这些矩阵分别命名为x1,x2,x3 ..... x999,x1000。 I have a custom function (fun1) that I run like this: 我有一个这样运行的自定义函数(fun1):
result<-sapply(list1,fun1)
This function will then return the individual results of this function like this (Example): 然后,此函数将返回该函数的各个结果,如下所示(示例):
x1 x2 x3 x4 x5.... x999 x1000
3 2 0 0 2 .... 9 0
What I would like to do is remove from the list all those that return a result of '0' from fun1. 我想做的是从列表中删除所有从fun1返回结果为“ 0”的内容。 So above, I would remove (presumably among others in the list) x3, x4, x1000. 因此,在上面,我将删除(可能是列表中的其他内容)x3,x4,x1000。 Ideally, the new list created (list2) following the removal of matrices that return 0s from fun1 would keep the original names (x1, x2 etc.). 理想情况下,删除从fun1返回0的矩阵后创建的新列表(list2)将保留原始名称(x1,x2等)。
I have struggled with working out how to do this. 我一直在努力寻找如何做到这一点。 I have thought about trying to make a function that would be applied to the 'result' object that uses ifelse to see if a 0 is contained, before then applying another function that removes the matrix from list1: 我考虑过尝试制作一个函数,该函数将应用于使用ifelse来查看是否包含0的“结果”对象,然后再应用另一个从list1中删除矩阵的函数:
sapply(result, fun.remove)
fun.remove <- function(x){
ifelse (result = 0,
function.delete.matrix,
NA))
}
I'm not sure what should go in the function.delete.matrix, or if using ifelse is even the best way to go about it. 我不确定在function.delete.matrix中应该包含什么内容,或者不确定是否使用ifelse是解决该问题的最佳方法。
Thanks for any suggestions. 感谢您的任何建议。
You can do this with simple subsetting 您可以通过简单的子集来做到这一点
list2 <- list1[result!=0]
Here's some sample data: 以下是一些示例数据:
set.seed(15)
list1<-as.list(rpois(20,1));
names(list1)<-paste0("x", seq_along(list1))
and let 然后让
fun1<-function(x) x;
result<-sapply(list1,fun1)
so 所以
list1[result==0]
shows all the elements with 0 values 显示所有值为0的元素
and 和
list1[result!=0]
shows those that do not have 0s. 显示没有0的那些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.