一个向量条件的另一个向量值的求和值

时间:2013-08-10 18:35:31

标签: r vector

在某些情况下,我试图将芝加哥小熊队的所有主场胜利加起来。因此,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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用ifelse代替if

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

示例:

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

<强> ifelse

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