我正在处理一些数据,并尝试进行一些条件过滤。我想写一条语句来评估一个变量是否等于数字(在这种情况下为1),如果是,则根据另一列的值进行过滤。结果应该是,所有AtBatPitchSequences == 1也都具有PitchType ==“ FA”。
我的数据(firsttwopitches)如下所示:
YearID GameID GamePitchSequen~ PAofInning AtBatPitchSeque~ Inning Balls Strikes PitchType
<dbl> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>
1 2018 DFCBC~ 1 1 1 1 0 0 FA
2 2018 DFCBC~ 2 1 2 1 1 0 FA
3 2018 DFCBC~ 4 2 1 1 0 0 FA
4 2018 DFCBC~ 5 2 2 1 0 1 SI
5 2018 DFCBC~ 8 3 1 1 0 0 FA
6 2018 DFCBC~ 9 3 2 1 0 1 FA
为了解决这个问题,我尝试使用if语句:
library(tidyverse)
firsttwopitches %>%
if (AtBatPitchSequence == 1) {
filter(PitchType == "FA")
}
但是,这会引发错误和警告:
Error in if (.) AtBatPitchSequence == 1 else { :
argument is not interpretable as logical
In addition: Warning message:
In if (.) AtBatPitchSequence == 1 else { :
the condition has length > 1 and only the first element will be used
我不明白为什么我的论点不能解释为逻辑。在我的脑海中,它应该评估AtBatPitchSequence是否等于1,然后继续进行下一行。另外,警告消息是什么意思?如果通过更正我的if语句来解决此警告,请不要担心,但我仍然是新手,并且正在尝试更好地调试自己的工作。我在if / while(条件)中通读了此错误:参数不能解释为逻辑问题,其他人则无法尝试查找我的错误,但未成功。
非常感谢你
我们可以&
在filter
library(dplyr)
firsttwopitches %>%
filter(AtBatPitchSequence == 1, PitchType == "FA")
如果我们要保留“ AtBatPitchSequence”不等于1的行,则添加另一个表达式 |
firsttwopitches %>%
filter((AtBatPitchSequence == 1 & PitchType == "FA")|AtBatPitchSequence != 1)
有两个问题-1)if/else
没有向量化,2)与代码的阻塞有关,{}
尤其是在管道(%>%
)中使用代码时。一个相关的问题也是在寻找列名AtBatPitchSequence
外的tidyverse功能,即mutate
,summarise
等等。在这种情况下,我们需要指定数据,以及.$AtBatPitchSequence
错误/警告可以通过内置的数据集重现
data(iris)
head(iris) %>%
if(Species == 'setosa') {
filter(Petal.Length > 1.5)
}
if(。)Species ==“ setosa” else {:不能解释为逻辑错误此外:警告消息:if(。)Species ==“ setosa” else {:条件的长度> 1,并且只有将使用第一个元素
现在,我们可以通过在内进行阻塞来消除错误{}
,但请注意,警告仍然保持为if/else
未向量化状态,这也会产生错误的输出(下面的输出是正确的,但这仅是因为只有一行具有TRUE条件)遇见)
head(iris) %>%
{if(.$Species == 'setosa') {
filter(., Petal.Length > 1.5)
}}
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.4 3.9 1.7 0.4 setosa
警告消息:在if(。$ Species ==“ setosa”){中:条件的长度> 1,并且仅使用第一个元素
如果我们在使用多个表达式filter
(,
将生成&
)
head(iris) %>%
filter(Species == 'setosa', Petal.Length > 1.5)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.4 3.9 1.7 0.4 setosa
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句