r - How to subset matrices in an list in R?
问题描述
Currently, I have a list of 500 elements, named List.500
. In each list, I have 3 vectors and 1 matrix. The first element is:
> List.500[[1]]
$two_values
$two_values$bin
[1] 0 1
$grid_points$grid
[1] 0.05000000 0.06836735 0.08673469 0.10510204 0.12346939 0.14183673 0.16020408
[8] 0.17857143 0.19693878 0.21530612 0.23367347 0.25204082 0.27040816 0.28877551
$mean_0
[1] 14.48597 14.49662 14.51089 14.52915 14.55242 14.58129 14.61866 14.66572 14.72186
[10] 14.79531 14.88589 14.99356 15.13048 15.29701
$mean_1
[1] 16.48597 16.49662 16.51089 16.52915 16.55242 16.58129 16.61866 16.66572 16.72186
[10] 16.79531 16.88589 16.99356 17.13048 17.29701
$mean_grid
g=0.05 g=0.07 g=0.09 g=0.11 g=0.12 g=0.14 g=0.16 g=0.18 g=0.2
bin=0 14.48597 14.49662 14.51089 14.52915 14.55242 14.58129 14.61866 14.66572 14.72186
bin=1 16.48597 16.49662 16.51089 16.52915 16.55242 16.58129 16.61866 16.66572 16.72186
g=0.22 g=0.23 g=0.25 g=0.27 g=0.29
bin=0 14.79531 14.88589 14.99356 15.13048 15.29701
bin=1 16.79531 16.88589 16.99356 17.13048 17.29701
I would like to subset out only the 1st, 2nd, and 3rd elements from each of the 2 vectors (not including the first vector named two_values$bin
and 1 matrix (1st, 2nd, 3rd columns), for each of the 500 elements of List.500
. I want to leave two_values$bin
alone.
Ideally, I would like to get:
> List.500[[1]]
$two_values
$two_values$bin
[1] 0 1
$grid_points$grid
[1] 0.05000000 0.06836735 0.08673469
$mean_0
[1] 14.48597 14.49662 14.51089
$mean_1
[1] 16.48597 16.49662 16.51089
$mean_grid
g=0.05 g=0.07 g=0.09
bin=0 14.48597 14.49662 14.51089
bin=1 16.48597 16.49662 16.51089
for each of the 500 elements in List.500
. Is there a simple way to do this without resorting to breaking the list apart and looping? Thanks.
解决方案
如评论所述,您可以使用rapply
. 我认为您列表中的元素遵循某种模式,但出于演示的目的,我使用了以下数据。
set.seed(123)
List.500 <- lapply(1:3, function(x) list(two_values = list(bin = 0:1),
grid_points = list(grid = runif(16, 0,.3)),
mean_0 = runif(14, 14, 16),
mean_1 = runif(14, 16, 18),
mean_grid = matrix(runif(28, 14, 18), nrow = 2, byrow = TRUE)))
以下代码将完全符合您的要求。
rapply(List.500,
function(x) {if(is.matrix(x)) {x[,1:3]} else {
if(length(x) == 2) {x} else {x[1:3]}
}},
how = "replace")
推荐阅读
- fish - Fish如何防止递归函数调用
- mysql - Laravel - 如何获得两条记录之间的最近时间
- php - 流明定制服务商
- git - GitLab:如何从 git 远程存储库中仅提取所需的文件夹
- reactjs - 'album' 未在 defaultValues 中定义,useForm()
- jquery - 通过具有子函数的函数扩展 Jquery 函数
- javascript - 在将元素附加到 DOM 之后调用 getBoundingClientRect()
- python - 如何绘制轴对象?
- azure - 在 azure 消费使用详情 api 中,metric 类型 actualcost、usagecost 和 amortizedcost 有什么区别?
- sql - 连接表以获取空行