将矩阵转换为一维数组

发布于 2024-09-25 13:59:34 字数 43 浏览 2 评论 0原文

我有一个矩阵(32X48)。

如何将矩阵转换为一维数组?

I have a matrix (32X48).

How can I convert the matrix into a single dimensional array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

合久必婚 2024-10-02 13:59:34

要么用“scan”读取它,要么只在矩阵上执行 as.vector() 。如果您想要按行或按列转置矩阵,您可能需要先转置矩阵。

> m=matrix(1:12,3,4)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> as.vector(m)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
> as.vector(t(m))
 [1]  1  4  7 10  2  5  8 11  3  6  9 12

Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.

> m=matrix(1:12,3,4)
> m
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
> as.vector(m)
 [1]  1  2  3  4  5  6  7  8  9 10 11 12
> as.vector(t(m))
 [1]  1  4  7 10  2  5  8 11  3  6  9 12
岁月流歌 2024-10-02 13:59:34

尝试c()

x = matrix(1:9, ncol = 3)

x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

c(x)

[1] 1 2 3 4 5 6 7 8 9

try c()

x = matrix(1:9, ncol = 3)

x
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

c(x)

[1] 1 2 3 4 5 6 7 8 9
猫卆 2024-10-02 13:59:34

如果我们谈论的是 data.frame,那么你应该问自己这些变量是同一类型的吗?如果是这种情况,您可以使用 rapply 或 unlist,因为 data.frames 是列表,在其灵魂深处......

 data(mtcars)
 unlist(mtcars)
 rapply(mtcars, c) # completely stupid and pointless, and slower

If we're talking about data.frame, then you should ask yourself are the variables of the same type? If that's the case, you can use rapply, or unlist, since data.frames are lists, deep down in their souls...

 data(mtcars)
 unlist(mtcars)
 rapply(mtcars, c) # completely stupid and pointless, and slower
甲如呢乙后呢 2024-10-02 13:59:34

array(A)array(t(A)) 将为您提供一个一维数组。

array(A) or array(t(A)) will give you a 1-d array.

々眼睛长脚气 2024-10-02 13:59:34

您可以使用as.vector()。根据我的小基准,它看起来是最快的方法,如下所示:

library(microbenchmark)
x=matrix(runif(1e4),100,100) # generate a 100x100 matrix
microbenchmark(y<-as.vector(x),y<-x[1:length(x)],y<-array(x),y<-c(x),times=1e4)

第一个解决方案使用 as.vector(),第二个解决方案使用矩阵作为连续数组存储在内存中的事实length(m) 给出矩阵 m 中的元素数量。第三个从 x 实例化一个 array,第四个使用连接函数 c()。我也尝试过来自gdataunmatrix,但是太慢了,这里就不提了。

以下是我获得的一些数值结果:

> microbenchmark(
        y<-as.vector(x),
        y<-x[1:length(x)],
        y<-array(x),
        y<-c(x),
        times=1e4)

Unit: microseconds
                expr    min      lq     mean  median      uq       max neval
   y <- as.vector(x)  8.251 13.1640 29.02656 14.4865 15.7900 69933.707 10000
 y <- x[1:length(x)] 59.709 70.8865 97.45981 73.5775 77.0910 75042.933 10000
       y <- array(x)  9.940 15.8895 26.24500 17.2330 18.4705  2106.090 10000
           y <- c(x) 22.406 33.8815 47.74805 40.7300 45.5955  1622.115 10000

展平矩阵是机器学习中的常见操作,其中矩阵可以表示要学习的参数,但使用通用库中的优化算法,该算法需要参数向量。因此,将矩阵(或多个矩阵)变换为这样的向量是很常见的。标准 R 函数 optim() 就是这种情况。

you can use as.vector(). It looks like it is the fastest method according to my little benchmark, as follows:

library(microbenchmark)
x=matrix(runif(1e4),100,100) # generate a 100x100 matrix
microbenchmark(y<-as.vector(x),y<-x[1:length(x)],y<-array(x),y<-c(x),times=1e4)

The first solution uses as.vector(), the second uses the fact that a matrix is stored as a contiguous array in memory and length(m) gives the number of elements in a matrix m. The third instantiates an array from x, and the fourth uses the concatenate function c(). I also tried unmatrix from gdata, but it's too slow to be mentioned here.

Here are some of the numerical results I obtained:

> microbenchmark(
        y<-as.vector(x),
        y<-x[1:length(x)],
        y<-array(x),
        y<-c(x),
        times=1e4)

Unit: microseconds
                expr    min      lq     mean  median      uq       max neval
   y <- as.vector(x)  8.251 13.1640 29.02656 14.4865 15.7900 69933.707 10000
 y <- x[1:length(x)] 59.709 70.8865 97.45981 73.5775 77.0910 75042.933 10000
       y <- array(x)  9.940 15.8895 26.24500 17.2330 18.4705  2106.090 10000
           y <- c(x) 22.406 33.8815 47.74805 40.7300 45.5955  1622.115 10000

Flattening a matrix is a common operation in Machine Learning, where a matrix can represent the parameters to learn but one uses an optimization algorithm from a generic library which expects a vector of parameters. So it is common to transform the matrix (or matrices) into such a vector. It's the case with the standard R function optim().

灼痛 2024-10-02 13:59:34

来自?matrix:“矩阵是二维‘数组’的特例。”您可以简单地更改矩阵/数组的维度。

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)

From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)
執念 2024-10-02 13:59:34

可能已经太晚了,无论如何,这是我将矩阵转换为向量的方法:

library(gdata)
vector_data<- unmatrix(yourdata,byrow=T))

希望会有所帮助

It might be so late, anyway here is my way in converting Matrix to vector:

library(gdata)
vector_data<- unmatrix(yourdata,byrow=T))

hope that will help

前事休说 2024-10-02 13:59:34

简单快速,因为一维数组本质上是一个向量

result <- matrix[1:length(matrix)]

Simple and fast since a 1d array is essentially a vector

result <- matrix[1:length(matrix)]
风向决定发型 2024-10-02 13:59:34

对于那些不仅想要生成数组,还想要生成具有相应行和列名称的数组的人,我建议使用 Melt 函数,如 这个答案。

library(reshape2)
df.L <- melt( df, id.vars="New_name4_rownames",
               value.name="NAME_of_VALUE", variable.name="New_name4_colnames" )
print(df.L)

然后您可以根据需要组合行和列的名称,并使用 spread/pivot_wider 使列名称成为矩阵的行+列名称和 1 行(即向量)的组合。

df.L$Both <- paste0(df.L$New_name4_rownames, "_", df.L$New_name4_colnames)
df.sel <- df.L[,3:4] #select only values and combined column names
output1d <- pivot_wider(data = df.sel, names_from = Both, values_from = NAME_of_VALUE)

For anyone looking to produce not just the array, but the array with the corresponding Row and Column names I recommend the melt function as in this answer.

library(reshape2)
df.L <- melt( df, id.vars="New_name4_rownames",
               value.name="NAME_of_VALUE", variable.name="New_name4_colnames" )
print(df.L)

And then you can combine the names of the row and column as you like and use spread/pivot_wider to have the column names be a combination of the row+column names of the matrix and 1 row which is your vector.

df.L$Both <- paste0(df.L$New_name4_rownames, "_", df.L$New_name4_colnames)
df.sel <- df.L[,3:4] #select only values and combined column names
output1d <- pivot_wider(data = df.sel, names_from = Both, values_from = NAME_of_VALUE)
银河中√捞星星 2024-10-02 13:59:34

您可以使用 Joshua 的解决方案,但我认为您需要 Elts_int <- as.matrix(tmp_int)

或者 for 循环:

z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {  
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}

z 是一维向量。

You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)

Or for loops:

z <- 1 ## Initialize
counter <- 1 ## Initialize
for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
for (x in 1:32) {  
z[counter] <- tmp_int[x,y]
counter <- 1 + counter
}
}

z is a 1d vector.

探春 2024-10-02 13:59:34

如果您有一个包含多列的 data.frame (df) 并且您想要矢量化,您可以执行

as.matrix(df, ncol=1)

If you instead had a data.frame (df) that had multiple columns and you want to vectorize you can do

as.matrix(df, ncol=1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文