Make two random teams forming the data set and get the total team score in R

Suppose I have a football team of 10 players (players), from which I have to make two subgroups of 5 players, and then calculate the total score for each team.

players <- read.table(text=
"paul    3
ringo   3
george  5
john    5
mick    1
ron     2
charlie 3
ozzy    5
keith   3
brian   3", as.is=TRUE)

I have already extracted a random set of 5 players:

t1 <- sample(players$V1, size = 5)

But you need to create a second team (excluding the players in the first) and counting the total score for both teams, I completed blocked.

+4
source share
3 answers

You can try to sample player indices to build the first team, instead of selecting names.

idx1 <- sample(1:nrow(players), 5)

In fact, you can use these indexes to get all the information about each command:

team1 <- players[idx1,]
team2 <- players[-idx1,]

sum(team1$V2) sum(team2$V2).

+6

data.table, - :

library(data.table)
##
(data.table(data)[
  ,team := sample(1:.N,.N) %% 2][
    ,list(
      score = sum(V2)), 
    by=team])
#      team  score
# 1:    0    14
# 2:    1    19

, .


, , ,

(data.table(data)[
  ,team := sample(1:.N,.N) %% 2][
    ,list(
      score = sum(V2),
      players = V1), 
    by=team])
#      team  score  players
# 1:    0    17     paul
# 2:    0    17     john
# 3:    0    17     mick
# 4:    0    17     ozzy
# 5:    0    17     brian
# 6:    1    16     ringo
# 7:    1    16     george
# 8:    1    16     ron
# 9:    1    16     charlie
# 10:   1    16     keith
+2

First, just get a random order.

> k <- sample(nrow(players))

Then, to get the names in each command, put the list in that order and put it in two columns.

> matrix(players$V1[k], ncol=2)
##     [,1]    [,2]     
## [1,] "keith" "charlie"
## [2,] "paul"  "john"   
## [3,] "ron"   "brian"  
## [4,] "mick"  "george" 
## [5,] "ozzy"  "ringo"  

To get the total, do the same with the estimates and calculate the sums of the columns.

> colSums(matrix(players$V2[k], ncol=2))
## [1] 14 19
+1
source

All Articles