逐行组合R列

时间:2013-05-23 21:49:21

标签: r

我有一个价值矩阵:

x<-matrix(rnorm(8),nrow=2,ncol=4,byrow=T)
           [,1]       [,2]       [,3]      [,4]
[1,] -0.1048800  0.4437521 -0.7768075 0.2820776
[2,]  0.0700801 -0.4621662 -0.7877975 0.4933406

我想让它看起来像这样:

           [,1]      
[1,] -0.1048800
[2,]  0.0700801
[3,]  0.4437521
[4,] -0.4621662
[5,] -0.7768075
[6,] -0.7877975
[7,]  0.2820776
[8,]  0.4933406

我试过了:

  temp<-c()
  for(l in 1:ncol(x)){
    temp<-rbind(temp,as.x[,l])
  }

但它不会使它工作。任何想法?

4 个答案:

答案 0 :(得分:4)

为什么不只是matrix(x,8,1)

x<-matrix(rnorm(8),nrow=2,ncol=4,byrow=T)
> matrix(x,8,1)
           [,1]
[1,] -1.2735095
[2,] -0.8340542
[3,] -1.0982551
[4,]  0.8774815
[5,]  1.0443129
[6,] -0.1672568
[7,] -0.3545977
[8,] -1.2148138

或者作为thelatemail注释,更通用matric(x,ncol = 1)

答案 1 :(得分:4)

我认为这样做:

x<-matrix(rnorm(8),nrow=2,ncol=4,byrow=T)
temp <- as.matrix(as.vector(x))

答案 2 :(得分:3)

记住矩阵是具有dim属性的载体......

您可以直接更改dim属性...

dim(x) <- c(ncol(x)*nrow(x),1)

答案 3 :(得分:2)

一种奇特的方式是使用attr,如:

> set.seed(1)
> x<-matrix(rnorm(8),nrow=2,ncol=4,byrow=T)
> attr(x, "dim") <- c(prod(dim(x)), 1)
> x
           [,1]
[1,] -0.6264538
[2,]  0.3295078
[3,]  0.1836433
[4,] -0.8204684
[5,] -0.8356286
[6,]  0.4874291
[7,]  1.5952808
[8,]  0.7383247