【发布时间】:2017-03-28 13:05:37
【问题描述】:
第一次在这里发帖,但我已经阅读了很多,所以谢谢!
我有一个包含许多列的巨大数据框,但这里只有 4 个重要:
dates/classes/names/grades.
对于每个日期,我有几个班级(有学生),每个班级都有几个人(名字 - 在各自班级中总是相同的人),每个班级每个日期都有一个成绩。
在第一次约会时,我使用max[] 检索每个班级考虑到他的成绩最好的学生。
但是,对于接下来的日期,我想做以下事情:
- 如果之前最好的学生仍然在班级前 3 名,那么我们认为他仍然是最好的。
- 否则,我们认为新的第一名学生是最好的。
因此,每个日期都取决于前一个日期。
是否可以在没有循环的情况下执行此操作?
我不知道如何,因为每次迭代都取决于前一次。
这是我下面的代码。 未优化请见谅!
非常感谢:)
for (i in (1:(length(horizon)-1))) #horizon is the vector of dates
{
uni3 <- dataaf[dataaf[,1] == as.numeric(horizon[i]),] #dataaf contains all the data, we only keep the date for the considered date i
if (i == 1) #we take the best student per class
{
selecdate <- data.frame() #selecdate is the dataframe containing the best people for this date
for (z in (1:15) #15 classes
{
selecsec <- na.omit(uni3[uni3[,14] == z,]) #classes are column 14
ligneselec <- max(selecsec[,13]) #grades are column 13
selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
selecdate <- rbind(selecdate,selecsec)
}
}
else { #we keep a student if he was in the previous top 3, else we take the best one
selecdate <- data.frame()
for (z in (1:15))
{
lastsec <- na.omit(lastdate[lastdate[,14] == z,]) #last results
#retrieving the top 3 people this date
selecsec <- na.omit(uni3[uni3[,14] == z,])
newligneselec <- tail(sort(selecsec[,13]),3)
selecsec <- data.frame(selecsec[rev(match(newligneselec,selecsec[,13])),])
if((length(match(selecsec[,3],lastsec[,3])[!is.na(match(selecsec[,3],lastsec[,3]))]) == 0))
{
ligneselec <- max(selecsec[,13])
selecsec <- data.frame(uni3[match(ligneselec,uni3[,13]),])
}
else
{
selecsec <- lastsec
}
selecdate <- rbind(selecdate,selecsec)
}
}
lastdate <- selecdate #recording the last results
}
编辑:这是一个例子。
- 在日期 1 中,约翰和奥黛丽都被选入了 1 和 2 类。
- 在第 2 天,约翰仍然是最好的 3 人之一,所以他仍然被选中, 而奥黛丽只有第四名,所以吉姆(在日期 2 中排名第一)取代 她。
-
在第 3 天,约翰仍然是最好的 3 人之一,因此他仍然被选中(我处理的数据中没有平局问题)。 Jim 现在是第 4 位,所以 Sandra 取代了他的位置。
结构(列表(日期=结构(c(1L,1L,1L,1L,1L,1L,1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("12/02", "13/02", "14/02" ), class= "因子"), 类 = c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2 ), 名称 = 结构 (c(6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L, 6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L, 6L, 3L, 9L, 7L, 1L, 8L, 4L, 10L, 5L, 2L), .Label = c("Ashley", "Audrey", "Bob", "Denis", “吉姆”,“约翰”,“金”,“桑德拉”,“特里”,“蒂姆”),class=“因素”), 等级 = c(10, 5, 3, 2, 1, 3, 4, 5, 6, 7, 8, 2, 10, 9, 1, 7, 5, 1, 8, 2, 5, 1, 4, 8, 8, 7, 6, 5, 4, 3)), .Names = c("日期", "Classes", "Names", "Grades"), row.names = c(NA, -30L), class= "data.frame")
【问题讨论】:
-
请提供一个最小的例子。
-
我无法插入表格...抱歉
-
在您的
data.frame上使用dput获取示例,请参阅here -
你想如何处理领带?
-
平局不会是问题,我在这里举了一个简单的例子,但不太可能有平局! @count 谢谢,我马上去查一下 :)