[英]Problem updating vector using for loop in R
I am trying to run code which calculates the number of home goals each team in the Premier League scored last season. 我正在尝试运行代码,以计算上赛季英超联赛中每支球队的主场进球数。 For some reason when I run the following for loop the vector OVHG's values don't change.
由于某些原因,当我运行以下for循环时,矢量OVHG的值不会改变。
install.packages("Hash")
library(hash)
fantasyData <- read.csv("PremierData.csv")
attach(fantasyData)
head(fantasyData)
teams = c("Arsenal", "Aston Villa", "Bournemouth", "Brighton", "Burnley", "Chelsea", "Crystal Palace", "Everton", "Leicester", "Liverpool",
"Man City", "Man United", "Newcastle", "Norwich", "Sheffield Wed", "Southampton", "Tottenham", "Watford", "West Ham", "Wolves")
values = seq(1, 20)
teamDict <- hash(teams, values)
OVHG = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0, 0, 0 ,0, 0, 0, 0,0, 0, 0, 0)
for (team in teams) {
for (i in 1:length(HomeTeam)) {
if (HomeTeam[i] == team) {
OVHG[teamDict$team] <- OVHG[teamDict$team] + FTHG[i]
}
}
}
There is no error message but the values of OVHG remain unchanged. 没有错误消息,但是OVHG的值保持不变。
OVHG [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
OVHG [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
You use vector operation for i
and then indexing with a logical vector ( i
): 您对
i
使用向量运算,然后使用逻辑向量( i
)进行索引:
# install.packages("hash")
library("hash")
### data from https://datahub.io/sports-data/english-premier-league
fantasyData <- read.csv("https://datahub.io/sports-data/english-premier-league/r/season-1819.csv", stringsAsFactors = FALSE)
Teams <- data.frame(teams = sort(unique(fantasyData$HomeTeam)), OVHG = 0, stringsAsFactors = FALSE)
values = seq(1, 20)
teamDict <- hash(Teams$teams, values)
for (team in Teams$teams) {
i <- (fantasyData$HomeTeam == team)
Teams$OVHG[teamDict[[team]]] <- Teams$OVHG[teamDict[[team]]] + sum(fantasyData$FTHG[i])
}
Teams
Using attach()
is often a bad idea; 使用
attach()
通常是一个坏主意; here is a short example of one attach-problem: 这是一个附加问题的简短示例:
B <- BOD;
attach(B);
demand[3] <- 999;
demand;
detach(B);
B
Also read fortunes::fortune(379)
另请阅读
fortunes::fortune(379)
without hash
you can do: 没有
hash
您可以执行以下操作:
fantasyData <- read.csv("https://datahub.io/sports-data/english-premier-league/r/season-1819.csv", stringsAsFactors = FALSE)
Teams <- data.frame(teams = sort(unique(fantasyData$HomeTeam)), stringsAsFactors = FALSE)
ovhg <- function(team) sum(fantasyData$FTHG[fantasyData$HomeTeam == team])
Teams$OVHG <- sapply(Teams$teams, ovhg)
Teams
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.