从R中较大的576x4矩阵创建多个较小的4x4矩阵

时间:2016-05-19 14:31:03

标签: r matrix

因此,今年我正致力于住宿生活,从事房间工作。因此,我获得了一个包含所有信息的大量excel文件。

我的工作是在每行[学生姓名]中再添加三列[三个室友的名字]。我已经使用excel中的CONCATENATE函数完成了这项工作。

我要核实我所有的房间分配都是正确的。以下是室友Joe,Moe,Poe,Zoe的数据:

Student Name        Roomate1      Roommate 2     Roomate 3
Joe                 Moe           Poe            Zoe
Moe                 Poe           Zoe            Joe
Poe                 Zoe           Joe            Moe
Zoe                 Joe           Moe            Poe

我发现,为了确保分配正确,我可以将矩阵与其转置进行比较,并且由于名称的排列方式,它们必须相同。

所以,提出问题

如果我有一个更大的4 x 576矩阵,我将如何创建多个较小的4 x 4矩阵,以便我可以执行检查每个较小矩阵是否等于的操作转置。

以下是我必须导入文件并清理数据。

#Reading data frame from file from .csv file
RoommateCheck <- read.csv("RoommateCheck.csv", header = TRUE)

#Converting Data Frame to Matrix
RoommateCheckMatrix <- as.matrix(RoommateCheck)

#Taking out useless data
RoommateCheckMatrix <- RoommateCheckMatrix[2:617,6:9]  

#Comparing the smaller matrices to their transposes
RoommateGroup == t(RoommateGroup)

我尝试创建两个向量,可以用来遍历更大的矩阵

x <- c(1 + 4 *(0:144))
y <- c(4 *(1:144))

for (i in x)
{
  for (j in y)
  {
    TempMatrix <- ResLifeNames[x:y,]
  }
}

但我一直收到警告:

 Warning messages:
 1: In x:y : numerical expression has 145 elements: only the first used  
 2: In x:y : numerical expression has 144 elements: only the first used

我不知道要修复。我的意图是有两个数字序列可以用作变量来限制要传输到Temp矩阵的行。

我查看了每个 apply 函数的说明,但找不到可以在这种情况下使用的函数。

1 个答案:

答案 0 :(得分:0)

使用as.is = TRUE读取问题中的数据,将其保留为字符数据并将其展开为8x4矩阵m,以便我们进行更多测试。

k为4x4矩阵的数量。在示例中,数据k为2。 将kx4矩阵m转换为4xkx4数组a,使得a[,1,]是第一个4x4矩阵,a[,2,]是第二个,如果m更大,则会继续上。现在{4}在4x4切片上apply给出一个长度为kis.sym的逻辑向量,其第i个分量为TRUE或FALSE,因为相应的4x4矩阵是对称的或不对称的。如果所有4x4矩阵都是对称的,all(is.sym)将是一个标量为TRUE。

# create 8x4 test matrix
Lines <- "StudentName        Roomate1      Roommate2     Roomate3
Joe                 Moe           Poe            Zoe
Moe                 Poe           Zoe            Joe
Poe                 Zoe           Joe            Moe
Zoe                 Joe           Moe            Poe"   
RoommateCheck <- read.table(text = Lines, header = TRUE, as.is = TRUE)
m <- as.matrix(RoommateCheck)
m <- rbind(m, m)

# reshape into array and apply function over 4x4 slices
k <- nrow(m) / 4
a <- array(m, c(4, k, 4))
is.sym <- apply(a, 2, function(x) identical(x, t(x)))
all(is.sym)