【发布时间】:2015-06-19 19:09:57
【问题描述】:
我有以下格式的数据
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, ] 要替换的项目数不是替换长度的倍数
谁能告诉我如何解决这个错误
感谢和问候
【问题讨论】:
-
我将
Course(在您的原始代码中)更改为Subject,因为它看起来像是一个错字。
标签: r matrix transpose insertion