0

I have a set of students c("John","Jeff","Jim","Jack","Joe","Jones") and each of them has attended in 3 different classes c("Math","Science","History") and achieved an natural number as score between 0 and 100.

Therefore, the table is supposed to be like

Name Class   Score
Jim  Math     25
Jim  History  60
Jim  Science  80
Jeff Math     85
Jeff History  40
Jeff Science  100
...
...
...

What i have tried is:

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),]

My code gives me:

   Names   Class Grades
4   Jack    Math     73
10  Jack    Math     87
16  Jack    Math     81
2   Jeff Science     24
8   Jeff Science     79

so, instead of Math, History, and Science, i have Math, Math, and Math.

But, it does not give me what i need. How can i fix it?

Jeff
  • 6,026
  • 20
  • 64
  • 108
  • 1
    but "Jack" has attended only "Math" how is he supposed to get other subjects? – Ronak Shah Sep 24 '18 at 12:48
  • What do you mean? What is your original dataset? If it is `dt`, then the output you get is correct – Sotos Sep 24 '18 at 12:48
  • @RonakShah Yes, that is why my code is wrong. I want `Jack` to have scores in `History`, and `Science` as well – Jeff Sep 24 '18 at 12:51
  • @Sotos i have no original dataset. I am trying o generate my dataset – Jeff Sep 24 '18 at 12:52
  • 1
    Ohh...I see. You are trying to "create" the data frame. Yup, you just need `each` in `rep` instead of `times`. – Ronak Shah Sep 24 '18 at 12:54
  • 1
    [Sequence of Repeated Values in R](https://stackoverflow.com/questions/6432067/sequence-of-repeated-values-in-r) – Henrik Sep 24 '18 at 12:56

1 Answers1

2

try using each in rep... best practice is to set each/times/length-out in rep explicitly, to avoid unexpected behaviour.

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
Wimpel
  • 16,956
  • 1
  • 15
  • 34