簡體   English   中英

在具有兩個邏輯值的向量上應用ifelse

[英]apply ifelse on a vector with two logical values

我有一個值向量,我想決定這個向量的哪些元素在某個區間內,哪些元素不是。

所以我做了以下事情:

vec <- ifelse( 1<va2<3, 1, 0);

但我收到一個錯誤說:vec中意外的'<'所以我嘗試了以下內容:

vec <- ifelse( 1<va2 && va2<3, 1, 0);

但它只給了我第一個價值。

那么如何讓ifelse使用兩個邏輯值,還是有其他選擇?

謝謝。

嘗試使用& not &&進行元素比較,它是在對元素向量進行邏輯比較時應該使用的。

> va2 <- c(2,1,4,2,6,0,3)
> ifelse( 1<va2 & va2<3, 1, 0)
[1] 1 0 0 1 0 0 0

從helpfile(參見?"&" )可以找到以下內容:

& and && indicate logical AND and | and || indicate logical OR. The shorter
form performs elementwise comparisons in much the same way as arithmetic 
operators. The longer form evaluates left to right examining only the first 
element of each vector. Evaluation proceeds only until the result is determined.
The longer form is appropriate for programming control-flow and typically 
preferred in if clauses.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM