我试图计算2014年世界杯小组赛阶段的最佳进球差距。
football <- read.csv(
file="http://pastebin.com/raw.php?i=iTXdPvGf",
header = TRUE,
strip.white = TRUE
)
football <- head(football,n=48L)
football[which(max(abs(football$home_score - football$away_score)) == abs(football$home_score - football$away_score)),]
结果
home home_continent home_score away away_continent away_score result
4 Cameroon Africa 0 Croatia Europe 4 l
7 Spain Europe 1 Netherlands Europe 5 l
37 Germany
所以那些目标最高的游戏是不同的,但现在我需要创建一个具有团队名称的新数据框,abs(football$home_score-football$away_score)
答案 0 :(得分:2)
football$score_diff <- abs(football$home_score - football$away_score)
football$winner <- ifelse(football$home_score > football$away_score, as.character(football$home),
ifelse(football$result == "d", NA, as.character(football$away)))
答案 1 :(得分:1)
你可以用这种方式保存一些打字。你首先获得分数差异和获胜者。当结果显示w
时,home就是赢家。所以你根本不需要考虑分数。添加分数差异和获胜者后,您可以通过使用max()
对数据进行分组来对数据进行分组。
mydf <- read.csv(file="http://pastebin.com/raw.php?i=iTXdPvGf",
header = TRUE, strip.white = TRUE)
mydf <- head(mydf,n = 48L)
library(dplyr)
mutate(mydf, scorediff = abs(home_score - away_score),
winner = ifelse(result == "w", as.character(home),
ifelse(result == "l", as.character(away), "draw"))) %>%
filter(scorediff == max(scorediff))
# home home_continent home_score away away_continent away_score result scorediff winner
#1 Cameroon Africa 0 Croatia Europe 4 l 4 Croatia
#2 Spain Europe 1 Netherlands Europe 5 l 4 Netherlands
#3 Germany Europe 4 Portugal Europe 0 w 4 Germany
答案 2 :(得分:1)
以下是另一个不使用ifelse
创建“获胜者”列的选项。这基于行/列索引。通过将结果列与其唯一元素(match(football$result,..
)匹配来创建数字列索引,行索引仅为1:nrow(football)
。将“足球”数据集与“主页”,“离开”和cbind
列进行子集,并使用附加列“绘制”使用NA,以便“结果”中的“d”元素更改为NA。
football$score_diff <- abs(football$home_score - football$away_score)
football$winner <- cbind(football[c('home', 'away')],draw=NA)[
cbind(1:nrow(football), match(football$result, c('w', 'l', 'd')))]
football[with(football, score_diff==max(score_diff)),]
# home home_continent home_score away away_continent away_score result
#60 Brazil South America 1 Germany Europe 7 l
# score_diff winner
#60 6 Germany
如果数据集非常大,您可以使用match
中的chmatch
来加快library(data.table)
library(data.table)
chmatch(as.character(football$result), c('w', 'l', 'd'))
注意:我在链接中使用了完整的数据集