【问题标题】:beginner rerrange data in a csv file初学者在 csv 文件中重新排列数据
【发布时间】:2013-04-10 12:52:36
【问题描述】:

这真的很基础,但我被过于复杂的代码卡住了。我有一个 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 循环造成的,但我不知道该怎么做。

【问题讨论】:

  • 停止时i的值是多少?那应该是导致错误的原因。你能展示那个子集吗?另外,为了清楚起见,您是否尝试用j 替换嵌套循环中的i

标签: r csv


【解决方案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

【讨论】:

  • 完美,这太容易了!谢谢!
猜你喜欢
  • 2021-12-28
  • 2015-08-28
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多