Wal*_*cio 2 boolean-logic r which
我总是使用这样的命令:
which(foo$bar == 'A' | foo$bar == 'B' | foo$bar == 'C')
Run Code Online (Sandbox Code Playgroud)
由于它们都与同一个变量相关,我希望能够清理我的代码并执行以下操作:
which(foo$bar == 'A|B|C') # such syntax works in grep, why not here?
# or...
which(foo$bar == c('A', 'B', 'C'))
Run Code Online (Sandbox Code Playgroud)
但这一切都不起作用!我很确定必须有一个简单的解决方案,我找不到它.我在ifelse()功能方面遇到同样的问题,因此通用解决方案的额外吹嘘权利.
with(foo, which(bar %in% LETTERS[1:3]) )
Run Code Online (Sandbox Code Playgroud)
可用于从数据框中选择行.也可以使用它作为报告矢量的逻辑索引,尽管使用逻辑索引你需要记住R索引不是基于0的:
set.seed=(123)
foo <- data.frame(bar=sample(LETTERS[1:15], 10))
c("Not in A|B|C", "In A|B|C") [ 1+ foo$bar %in% LETTERS[1:3] ]
Run Code Online (Sandbox Code Playgroud)