Converting vectors into 2D matrix [duplicate]

我的梦境 提交于 2019-12-25 16:51:12

问题


I have data that looks like this:

   total position division
 34        C      ATL
 34        C      CEN
 47        C       NE
 46        C       NW
 44        C      PAC
 42        C       SE
 57        D      ATL
 50        D      CEN
 44        D       NE
 52        D       NW
 42        D      PAC
 52        D       SE
 29        L      ATL
 34        L      CEN
 28        L       NE
 34        L       NW
 29        L      PAC
 24        L       SE
 26        R      ATL
 33        R      CEN
 25        R       NE
 29        R       NW
 24        R      PAC
 35        R       SE

I wish to transform it into a 2D matrix which can then be used for a Chi squared test. So, my input needs to look like:

division        position
            C       D       L       R
ATL         34      57      29      26
CEN         34      50      34      33
NE          47      44      28      25
NW          46      52      34      29
PAC         44      42      29      24
SE          42      52      24      35

In short, I need to make the values in one of the vectors column headers, and the values in the other vector row headers. The total value that occurs in each row should be moved to the intersection of the row and column headers in the resultant 2D matrix (e.g. 44 for NE and D).

The order doesn't really matter, any vector can be a row or column in the final matrix, and the input will always have three columns: total, foo and bar.

How can I accomplish this? I'd hate to have to resort to something procedural in R, and my skills in R are somewhat lacking at the moment.

Thanks.


回答1:


This is a basic reshape problem (see ?reshape for more information).

Using base R, you can do the following (assuming your data are called "mydf"):

> reshape(mydf, direction = "wide", idvar = "division", timevar = "position")
  division total.C total.D total.L total.R
1      ATL      34      57      29      26
2      CEN      34      50      34      33
3       NE      47      44      28      25
4       NW      46      52      34      29
5      PAC      44      42      29      24
6       SE      42      52      24      35

Alternatively, you can use xtabs as follows. Multiple values for a given combination would be summed:

> xtabs(total ~ division + position, mydf)
        position
division  C  D  L  R
     ATL 34 57 29 26
     CEN 34 50 34 33
     NE  47 44 28 25
     NW  46 52 34 29
     PAC 44 42 29 24
     SE  42 52 24 35



回答2:


Here's another approach by just making a matrix:

matrix(df$total, ncol=4, dimnames=list(unique(df$division), unique(df$position)))

##      C  D  L  R
## ATL 34 57 29 26
## CEN 34 50 34 33
## NE  47 44 28 25
## NW  46 52 34 29
## PAC 44 42 29 24
## SE  42 52 24 35


来源:https://stackoverflow.com/questions/16848483/converting-vectors-into-2d-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!