如何从R中的矩阵列表中的每个矩阵中删除列? [英] How to remove columns from each matrix in a list of matrices in R?

查看:125
本文介绍了如何从R中的矩阵列表中的每个矩阵中删除列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用R中的list函数不是很熟悉.这是我第一次使用矩阵列表.我正在尝试从矩阵列表中的每个矩阵中删除相同的列,但不确定如何将其与R中的索引一起使用.

I am not very familiar with using the list function in R. This is my first use of a list of matrices. I am trying to remove the same columns from each matrix in a list of matrices but I am not sure how this works with the indexing in R.

现在,我在列表中有8个矩阵.每个矩阵为[120,56].我想从每个矩阵中删除 rows 列17-40和49-56.因此,我将得到[120,24]的8个矩阵的列表.

Right now I have 8 matrices in a list. Each matrix is [120, 56]. I would like to remove rows columns 17-40 and 49-56 from each matrix. Therefore, I would end up with a list of 8 matrices of [120, 24].

这是我拥有的矩阵列表的一个示例:

Here is an example of the matrix list I have:

MatrixList <- list(maxT = matrix(1:56, 120, 56, byrow = TRUE),
        minT = matrix(1:56, 120, 56, byrow = TRUE),
        meanT = matrix(1:56, 120, 56, byrow = TRUE),
        rain24 = matrix(1:56, 120, 56, byrow = TRUE),
        rain5d = matrix(1:56, 120, 56, byrow = TRUE),
        maxT2 = matrix(1:56, 120, 56, byrow = TRUE),
        minT2 = matrix(1:56, 120, 56, byrow = TRUE),
        meanT2 = matrix(1:56, 120, 56, byrow = TRUE))

我知道这似乎是一个简单的问题,但是我是新手,并且不确定如何使用for循环和内部索引的组合来删除列.我宁愿学习如何有效地执行此操作,而不是分别对每个矩阵进行处理,然后创建列表.

I know this seems like a simple problem but I'm a novice and am just not sure how to use a combination of for loops and internal indexing to remove columns. I'd rather learn how to do this efficiently, rather than doing it for each matrix individually and then creating the list.

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thanks!

推荐答案

在通常情况下,@ DWin早早得到了一个很好的答案.这是我简单的主意更容易理解的一种选择.

As is often the case, @DWin gets in early with an excellent answer. Here is an alternative that my simple mind finds easier to comprehend.

您可以使用lapply遍历列表,然后使用[运算符进行标准子设置.

You can use lapply to traverse your list, and then standard subsetting using the [ operator.

我不喜欢使用[运算符作为函数(如@DWin所建议的那样),我更喜欢在lapply内编写一个匿名函数,该函数看起来就像您要转换列表中单个元素(即子集)所执行的操作单个矩阵):

Rather than using [ operator as a function (as @DWin suggests), I prefer writing an anonymous function inside lapply that looks exactly like the operation you would perform to transform a single element of your list (i.e. subset a single matrix):

mls <- lapply(MatrixList, function(x)x[-c(17:40, 49:56), ])
str(mls)

List of 8
 $ maxT  : int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ minT  : int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ meanT : int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ rain24: int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ rain5d: int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ maxT2 : int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ minT2 : int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...
 $ meanT2: int [1:88, 1:56] 1 1 1 1 1 1 1 1 1 1 ...

这篇关于如何从R中的矩阵列表中的每个矩阵中删除列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆