I am trying to fill a matrix with a sample of data:
Pays NbChambre Prix
1 Grèce 56 390
2 Grèce 471 468
3 Grèce 93 427
4 Grèce 56 369
5 Grèce 286 499
6 Grèce 282 526
7 Grèce 310 587
8 Grèce 300 534
9 Maroc 146 447
10 Maroc 250 482
11 Maroc 196 511
12 Maroc 324 532
13 Maroc 138 450
14 Maroc 400 569
15 Maroc 366 419
16 Maroc 300 421
17 Maroc 144 579
18 Maroc 330 598
19 Maroc 260 495
20 Maroc 170 730
21 Portugal 254 646
22 Portugal 140 652
23 Portugal 273 802
24 Portugal 260 761
25 Portugal 169 1101
26 Tunisie 225 434
27 Tunisie 225 489
28 Tunisie 250 436
29 Tunisie 550 399
30 Tunisie 800 477
31 Tunisie 150 375
32 Tunisie 425 486
33 Tunisie 366 447
34 Tunisie 200 473
35 Tunisie 130 495
36 Turquie 500 617
37 Turquie 50 489
38 Turquie 232 520
39 Turquie 110 534
I need to fill a matrix with the values of the vector NbChambre
BUT in a way
that each row is used for a certain Pays
. The dimensions of the matrix would be
nrow=length(unique(Pays)),ncol=max(table(Pays))
I need to find a way to fill the matrix such as R automatically puts
NA or 0 or whatever to finish a row when there is not enough data and then skip line to continue with the vector NbChambre
. I'm relatively new to R so I really can't seem to find any way to do this.
The result should look like
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
[1,] 56 471 93 56 286 282 310 300 NA NA NA NA
[2,] 146 250 196 324 138 400 366 300 144 330 260 170
[3,] 254 140 273 260 169 NA NA NA NA NA NA NA
[4,]
[5,] and so on
I would really like if someone could help me, thank you!
xtabs
is built for this sort of thing:xtabs(NbChambre ~ Pays + ave(Pays, Pays, FUN = seq_along), df)
– alistaire