在R语言的which()和ifelse()函数中,如何组合逻辑语句?

3

我经常使用这样的命令:

which(foo$bar == 'A' | foo$bar == 'B' | foo$bar == 'C')

由于它们都涉及相同的变量,我想整理我的代码并像这样做:

which(foo$bar == 'A|B|C')  # such syntax works in grep, why not here?
# or...
which(foo$bar == c('A', 'B', 'C'))

但是这些都不起作用!我相信一定有一个简单的解决方案,只是我找不到。在ifelse()函数中也有同样的问题,所以如果能提供通用解决方案,就可以额外炫耀一下了。
3个回答

10
with(foo, which(bar %in% LETTERS[1:3]) )

可以用来从数据框中选择行。也可以将其用作逻辑索引到报告向量,但是请记住,在使用逻辑索引时,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] ]

+1 - 对于最后一位的备选(在我看来更好的)设计是将其存储为逻辑值:foo$in.ABC <- foo$bar %in% LETTERS[1:3] - flodel

3
根据@baptiste的意见
    mydata<-structure(list(y = c("A", "B", "C", "D", "E")), 
     .Names = "y", class = "data.frame", row.names = c(NA, -5L))
mydata
  y
1 A
2 B
3 C
4 D
5 E

三种解决方案:
a) 使用 ifelse
with(mydata,ifelse(y %in% c("A","B","C"),1,0))

b) using which

with(mydata,which(y %in% c("A","B","C")))

c)使用match

with(mydata,match(y,c("A", "B", "C")))

0

使用逻辑版本的 grep

foo <- letters[1:5]
foo[grepl("[a-c]", foo )]
seq_along(foo)[grepl("[a-c]", foo )]

你的第二个问题 - 这是你想要的吗:

ifelse (sum(grepl("[a-c]", foo ))==3, "abc present", "abc absent")

(使用 sum 将逻辑值转换为数值)

或者如果任何一个字母存在,执行某些操作:

if ( any(letters[1:3] %in% foo) ) print("abc present")

1
我认为问题是,如果它们中的任何一个存在,则代码将有微小的更改。ifelse (sum(grepl("[a-c]", foo )) > 0, "abc 存在", "abc 不存在") - Rohit Das

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接