,我有以下格式的数据插入可变长串的R用一个二维矩阵
Reg_No Subject
AA11 Physics
AA11 Chemistry
AA12 English
AA12 Maths
AA12 Physics
我想这个数据转换成排明智
Physics Chemistry
English Maths Physics
我知道,每个学生都能最多8个科目
我想创建一个矩阵,可以将上述数据存储为变量行(每个学生有不同数量的主题)
我已经写以下代码
# read csv file
Term4 <- read.csv("Term4.csv")
# Find number of Students
Matrix_length <- length(unique(Term4$Reg_No))
# Uniquely store their reg number
Student <- unique(Term4$Reg_No)
# create matrix to be inserted as csv
out <- matrix(NA, nrow=Matrix_length , ncol=8) # max subjects = 8 so ncol =8
# iterate to get each reg number's subjects
for (n in 1:Matrix_length) {
y <- Term4[Term4[,"Reg_No"] == Student[n],]$Subject
# transpose Courses as a single column into row and insert it in the matrix
out[n,] <- t(y)
}
我正在以下错误在出
错误[N,] < - T(Y):
数目的要替换的项目不是替换长度的倍数
谁能告诉我如何在这个错误的工作
感谢和问候
的[尺寸不匹配当填充基质]可能重复(http://stackoverflow.com/questions/6916675/dimension-does-not-match-when-populating-matrix) – Armfoot
我将'Course'(在您的原始代码中)更改为'Subject',因为它看起来像一个错字。 – bgoldst