0

这真的很基本,但我被过于复杂的代码所困。我有一个 CSV 文件,其中包含一列测试、一列分数和一列学生。我想重新格式化数据,以便我有学生分数行和测试列。

我创建了一个单独的 csv,其中包含名为“students.csv”的学生(作为数字代码),因为现在这更容易。

我有 52 名学生和 50 次测试。

我可以得到以下与一个学生一起工作:

matricNumbers <- read.csv("students.csv")
students <- as.vector(as.matrix(matricNumbers))
students
data <- read.csv("marks.csv")
studentSubset <- data[data[2] == 1150761,] 
marksSubset <- as.vector(as.matrix(studentSubset[5]))
ll <- list()
ll<-c(list(marksSubset), ll)
dd<-data.frame(matrix(nrow=50,ncol=50))
for(i in 1:length(ll)){
  dd[i,] <- ll[[i]]

}
dd

但我似乎无法让这个for循环通过每个学生。

getMarks <-function(studentNumFile,markFile){

matricNumbers <- read.csv(studentNumFile)
students <- as.vector(as.matrix(matricNumbers))


data <- read.csv(markFile)

for (i in seq_along(students)){
    studentSubset <- data[data[2] == i,] 
    marksSubset <- as.vector(as.matrix(studentSubset[5]))
    ll <- list()
    ll<-c(list(marksSubset), ll)
    dd<-data.frame(matrix(nrow=52,ncol=50))
    for(i in 1:length(ll)){
        dd[i,] <- ll[[i]]
    }
}
return(dd)
}

getMarks("students.csv","marks.csv")

我收到错误消息:

Error in `[<-.data.frame`(`*tmp*`, i, , value = logical(0)) : replacement has 0 items, need 50

我确信这是由于嵌套for循环,但我无法弄清楚如何做到这一点。

4

1 回答 1

1

如果我正确理解了问题,您可以使用该reshape软件包来实现您想要的。由于您不提供样本数据,因此很难测试。dput( head( matricNumbers ) )为此, 我建议您将 的输出粘贴到上面的代码块中。

但是,您应该能够按照我对一些虚拟数据使用的这个简单示例进行操作。我想你可能只需要一行,你就可以忘记所有复杂的循环内容!

# These lines make some dummy data, similar to you matricNumbers (hopefully)
test = sort(sample(c("Biology","Maths","Chemistry") , 10 , repl = TRUE ))
students = unlist( sapply(table(test), function(x) { sample( letters[1:x] , x ) } ) )
names(students) <- NULL
scores <- data.frame( test , mark = sample( 40:100 , 10 , repl = TRUE ) , students )
scores
        test mark students
1    Biology   50        c
2    Biology   93        a
3    Biology   83        b
4    Biology   83        d
5  Chemistry   71        b
6  Chemistry   54        c
7  Chemistry   54        a
8      Maths   97        c
9      Maths   93        b
10     Maths   72        a



# Then use reshape to cast your data into the format you require
# I use 'mean' as the aggregation function. If you have one score for each student/test, then mean will just return the score
# If you do not have a score for a particular student in that test then it will return NaN
require( reshape )
bystudent <- cast( scores , students ~ test , value = "mark" , mean )
bystudent
  students Biology Chemistry Maths
1        a      93        54    72
2        b      83        71    93
3        c      50        54    97
4        d      83       NaN   NaN
于 2013-04-10T13:13:45.887 回答