0

在某些情况下,我试图将芝加哥小熊队的所有主场胜利加起来。因此,W_L 列指的是胜利(“W”)和失败(“L”)。此外,H_A 列指的是主场比赛(“H”)和客场比赛(“A”)。

当另一列的值为“H”时,我无法从一列添加值“W”的总数。下面是我尝试使用的代码。

setwd("blah blah blah")
br <- read.csv(file="Baseball-Reference.csv", h=T)

record <- function(){
wins <- sum(br$W_L[!is.na(br$W_L)] == "W")
losses <- sum(br$W_L[!is.na(br$W_L)] == "L")
wp <- round(wins/games, digits = 3)
home_wins <- if(br$H_A[!is.na(br$H_A)] == "H"){
    wins <- sum(br$W_L[!is.na(br$W_L)] == "W")}
}

如果我运行它,我会收到警告。

Warning message:
In if (br$H_A[!is.na(br$H_A)] == "H") { :
the condition has length > 1 and only the first element will be used
4

2 回答 2

2

你真的需要if声明吗?也许这也有效:

home_wins <- with(br, sum(W_L == "W" & H_A == "H"))
home_wins

或者只是快速计数,尽管没有将单独的结果分配给变量:

tt <- with(br, addmargins(table(W_L , H_A)))
tt
于 2013-08-10T19:43:12.630 回答
0

使用ifelse代替if

ifelse函数对向量执行元素条件评估:

例子:

x<-3
y<-c(1,2,3)

如果别的

ifelse(x==y,"good","bad")
    [1] "bad"  "bad"  "good"

如果

if (x ==y) "good" else "bad"
[1] "bad"
Warning message:
In if (x == y) "good" else "bad" :
  the condition has length > 1 and only the first element will be used
于 2013-08-10T18:38:45.913 回答