本文介绍了将向量转换为2D矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下数据:

   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

我希望将其转换为2D矩阵,然后将其用于卡方检验.因此,我的输入应如下所示:

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

简而言之,我需要在向量列标题之一中创建值,并在其他向量行标题中创建值.每行中出现的总值应移动到结果2D矩阵中行标题和列标题的交点(例如,对于NE和D为44).

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).

顺序并不重要,任何向量都可以是最终矩阵中的行或列,并且输入将始终具有三列:total,foo和bar.

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.

我该怎么做?我讨厌不得不诉诸于R中的过程性程序,而我目前在R中的技能有些欠缺.

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.

谢谢.

推荐答案

这是一个基本的reshape问题(有关更多信息,请参见?reshape).

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

使用基数R,您可以执行以下操作(假设您的数据称为"mydf"):

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

或者,您可以按以下方式使用xtabs.给定组合的多个值将相加:

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

这篇关于将向量转换为2D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:37