应用于将列表中的指定矩阵元素转换为NA [英] lapply to turn specified matrix elements within list to NA
本文介绍了应用于将列表中的指定矩阵元素转换为NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个矩阵列表(玩具示例):
I have a list of matrices (toy example):
x <- matrix(1:20, nrow = 2, ncol = 10)
y <- matrix(1:20, nrow = 2, ncol = 10)
l <- list(x ,y)
我需要将> = 11的某些元素转换为NA.
I need to turn some elements >= 11 into NA.
在列表之外,我只会使用
Outside of the list I would just use
x[(x>= 11)] <- NA
,但是尝试应用相同的函数似乎将其作为一个整体应用于每个矩阵(即,每个矩阵都变成单个NA值).
but trying to lapply the same function appears to apply it to each matrix as a whole (ie each matrix turns into a single NA value).
l_na <- lapply(l, function(x) x[(x >= 11)] <- NA)
我显然对误会有所误解.一个解决方案以及我在这里出错的任何指针将不胜感激.
I'm clearly misunderstanding something about lapply. A solution and any pointers of what I am getting wrong here would be appreciated.
推荐答案
有效
l_na <- lapply(l, function(x) { x[(x >= 11)] <- NA; x })
l_na
##[[1]]
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##[1,] 1 3 5 7 9 NA NA NA NA NA
##[2,] 2 4 6 8 10 NA NA NA NA NA
##
##[[2]]
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##[1,] 1 3 5 7 9 NA NA NA NA NA
##[2,] 2 4 6 8 10 NA NA NA NA NA
添加x
作为上述返回值是一种选择.我不知道是否还有其他人.
Adding the x
as a return value like above is one option. I don't know if there are others.
这篇关于应用于将列表中的指定矩阵元素转换为NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文