[英]Fill in a list of matrices in R
I want to give a constant columns value to every matrices in a list of matrices. 我想给矩阵列表中的每个矩阵一个恒定的列值。 Here is the list of matrices.
这是矩阵列表。
list_matrix_Tanzania_Mod <- lapply(1:4, function(i)
matrix(sample(1:50, 4*10, replace=TRUE),
ncol=4, dimnames=list(NULL, LETTERS[1:4])))
Here is one matrix's example. 这是一个矩阵的例子。
[[1]]
A B C D
[1,] 15 31 5 16
[2,] 12 19 28 12
[3,] 36 34 37 19
[4,] 26 34 7 8
[5,] 34 17 12 47
[6,] 47 46 35 11
[7,] 14 10 4 37
[8,] 39 3 30 32
[9,] 41 26 32 35
[10,] 13 7 3 49
I want the column D in each matrices to get the values Modis500_2000
instead of the numbers. 我希望每个矩阵中的列D获得值
Modis500_2000
而不是数字。
I also want the column C to be equal to AB. 我也希望列C等于AB。 For instance, in the matrix example above, I want the column C in the row one to get the value 1531 instead of 5.
例如,在上面的矩阵示例中,我希望第一行中的列C获得值1531而不是5。
I read your previous question ( Add new columns to every matrices in a list of matrices in R ) and I would highly suggest that you switch to using data.frames instead of matrices. 我读了您先前的问题( 在R矩阵列表中的每个矩阵中添加新列 ),我强烈建议您切换到使用data.frames而不是矩阵。 It is in my opinion a better data structure for your type of work.
我认为这是适合您的工作类型的更好的数据结构。 Then you can use a function like
transform
to add/modify columns, in a rather simple and intuitive way: 然后,您可以使用诸如
transform
类的函数以一种非常简单直观的方式来添加/修改列:
list_matrix_Tanzania_Mod <- lapply(list_matrix_Tanzania_Mod,
transform,
C = A * B,
D = Modis500_2000,
E = A + B)
This will modify two columns ( C
and D
) and add one ( E
). 这将修改两列(
C
和D
)并添加一列( E
)。
If you ever need to convert your data back to matrices, then you can do: 如果您需要将数据转换回矩阵,则可以执行以下操作:
list_matrix_Tanzania_Mod <- lapply(list_matrix_Tanzania_Mod,
data.matrix)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.