3

いくつかのゲームのデータがあります。すべてのゲームで、さまざまな数のプレーヤーがゴールを決めました。ここで、すべてのゲームのゴール数を、そのゲームに参加したプレーヤーに配布したいと考えています。最後に、すべてのプレーヤーがすべてのゲームで獲得したゴールの合計を取得したいと思います。

Game 1: Players A + B + C; Goals: 3; so everyone gets a score of 1
Game 2: Players A + B + D + E; Goals: 8; everyone gets a score of 2
Game 3: Players B + C; Goals: 4; everyone gets a score of 2

結果:(これは作成したい場合です)

A: 3
B: 5
C: 3
D: 2
E: 2

このデータは CSV で利用できます。ここでは、ゲームごとの変数プレイヤーがパイプ (|) で区切られた 1 つの列に入れられます。

Players;Goals
A|B|C;3
A|B|D|E;8
B|C;4
E;3

これを data.frame に読み込むことができます。

data <- read.csv("demo.csv", header=TRUE, sep=";")

また、data.frame の Players 列からプレーヤー情報を分離します。

lapply(data$Players, function(x) strsplit(as.character(x), "|", fixed=TRUE))

ゴール列のスコアをこれらのプレーヤーに分配するにはどうすればよいですか?

4

1 に答える 1

2

base関数 andを使用したものを次に示し*applyます。

#input data (from clipboard)
data <- read.table(header=TRUE,sep=";",file='clipboard')
players <- strsplit(as.character(data$Players),"|",fixed=TRUE)
#number of players in a game
data$n.player <- sapply(players,length)
#unique list of players
uni.players <- unique(unlist(players))

goals.per.player <- sapply(uni.players,function(x) {
  #identifies which games (rows of data) each player was in
  games.played <- which(sapply(players, function(y) x %in% y))
  #sums the games played
  sum((data$Goals/data$n.player)[games.played])
})
#A B C D E 
#3 5 3 2 5
于 2013-01-24T16:13:39.713 に答える