将矩阵的每一列从数字转换为 R 中的整数

Transform every column of a matrix from numerics to integers in R

我需要将 R 矩阵对象的每一列从数字转换为整数。

矩阵描述:

> dim(path_abundances)
202  48

看起来像这样(但有 202 行和 48 列):

当寻找其他用户在这里提出的问题时,我发现这个解决方案可以将名为“dades”的矩阵的第 2 列到第 13 列从数字转换为整数(我想要的倒数):

dades[2:13] <- lapply(dades[2:13], as.numeric)

适用于我的具体情况,我试过:

> path_abundances[1:202] <- lapply(path_abundances[1:202], as.integer)

在查找输出时,它是一个包含 202 个元素的列表,其中每个元素都是第一列第 i 行的值,但没有小数点(正如预期的整数):

  1. 512884
  2. 379358
  3. 319740
  4. 等等

如上所述,我想将矩阵中的每一列转换为整数 -class 输出。

感谢您的阅读和提前的回答

-- 编辑以添加示例:

matrix(data= c(path_abundances[1:3,2], path_abundances[1:3,3], path_abundances[1:3,4]), ncol = 3, byrow = F)

         [,1]     [,2]     [,3]
[1,] 512884.5 493049.7 577625.5
[2,] 379358.8 343425.7 394776.8
[3,] 319740.8 327932.6 417228.9

我想要这个矩阵,每一列都是数字-class,每一列都是整数-class

您可以使用 storage.mode:

set.seed(101); m <- matrix(rnorm(9,mean=20,sd=3), 3,3)
storage.mode(m) <- "integer"
m
     [,1] [,2] [,3]
[1,]   19   20   21
[2,]   21   20   19
[3,]   17   23   22

请注意,这将截断而不是四舍五入为整数 - 以防对您重要。