gpt4 book ai didi

r - 将值分发给任意数量的接收者

转载 作者:行者123 更新时间:2023-12-01 13:33:19 24 4
gpt4 key购买 nike

我有一些比赛的数据,在这些比赛中,每场比赛都有不同数量的球员进球。我现在想将每场比赛的进球数分配给参加那场比赛的球员。最后我想得到每个球员在所有比赛中的进球总和。

示例:

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 格式提供,其中每场比赛的变量玩家被放入由竖线 (|) 分隔的单个列中:

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 中的玩家列分开:

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

我如何将目标列中的分数分配给这些玩家?

最佳答案

这是使用 base 函数和 *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

关于r - 将值分发给任意数量的接收者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14505430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com