Jeff
Jeff

Reputation: 8431

How to create a dataset in a specific structure?

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?

Upvotes: 0

Views: 43

Answers (1)

Wimpel
Wimpel

Reputation: 27772

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

Upvotes: 2

Related Questions