我有一组学生c("John","Jeff","Jim","Jack","Joe","Jones")
,他们每个人都参加了3个不同的班级c("Math","Science","History")
,并取得了自然分数,分数在0到100之间。
因此,表应该像
Name Class Score
Jim Math 25
Jim History 60
Jim Science 80
Jeff Math 85
Jeff History 40
Jeff Science 100
...
...
...
我尝试过的是:
dt<-data.frame(
Names=rep(c("John","Jeff","Jim","Jack","Joe","Jones"),3 ),
Class=rep(c("Math","Science","History"),6 ),
Grades=sample(1:100,18 ))
dt[sort(dt$Names),]
我的代码给了我
Names Class Grades
4 Jack Math 73
10 Jack Math 87
16 Jack Math 81
2 Jeff Science 24
8 Jeff Science 79
因此,我有Math
,History
和Science
,而不是Math
,Math
和Math
。
但是,它不能满足我的需求。我该如何解决?
答案 0 :(得分:2)
尝试在each
中使用rep
...最佳做法是将each
中的times
/ length-out
/ rep
显式设置为避免意外的行为。
data.frame(
Names=rep( c("John","Jeff","Jim","Jack","Joe","Jones"), each = 3 ),
Class=rep(c("Math","Science","History"), times = 6 ),
Grades=sample( 1:100,18 ) )
# Names Class Grades
# 1 John Math 57
# 2 John Science 23
# 3 John History 82
# 4 Jeff Math 3
# 5 Jeff Science 65
# 6 Jeff History 37
# 7 Jim Math 95
# 8 Jim Science 39
# 9 Jim History 16
# 10 Jack Math 18
# 11 Jack Science 63
# 12 Jack History 53
# 13 Joe Math 90
# 14 Joe Science 11
# 15 Joe History 77
# 16 Jones Math 29
# 17 Jones Science 15
# 18 Jones History 19