简体   繁体   English

如何使用R中的ifelse条件从向量中删除

[英]How to delete from vector using ifelse condition in R

I have a vector a with values (1,2,3,4) and another vector b with values (1,1,0,1).我有一个值为 (1,2,3,4) 的向量 a 和另一个值为 (1,1,0,1) 的向量 b。 Using the elements in b as a flag, I want to remove the vector elements from A at the same positions where 0 is found in element b.使用 b 中的元素作为标志,我想在元素 b 中找到 0 的相同位置从 A 中删除向量元素。

  a <- c(1,2,3,4)
  b <- c(1,1,0,1)
     for(i in 1:length(b))
  {
    if(b[i] == 0)
    {
      a <- a[-i]
    }
  }

I get the desired output我得到了想要的输出

a [1] 1 2 4 [1] 1 2 4

But using ifelse, I do not get the output as required.但是使用 ifelse,我没有得到所需的输出。

    a <- c(1,2,3,4)
  b <- c(1,1,0,1)
    for(i in 1:length(b))
    {
      a <- ifelse(b[i] == 0,a[-i],a)
    }

Output:输出:

a [1] 1 [1] 1

How to use ifelse in such situations?在这种情况下如何使用 ifelse?

I think ifelse isn't the correct function here since ifelse gives output of same length as input and we want to subset values here.我认为ifelse在这里不是正确的函数,因为ifelse给出与输入相同长度的输出,我们想在这里对值进行子集化。 You don't need a loop as well.您也不需要循环。 You can directly do你可以直接做

a[b != 0]
#[1] 1 2 4

data数据

a <- 1:4
b <- c(1, 1, 0, 1)

Another option could be:另一种选择可能是:

a[as.logical(b)]

[1] 1 2 4

If you want to use ifelse , you can use the following code如果要使用ifelse ,可以使用以下代码

na.omit(ifelse(b==0,NA,a))

such that以至于

> na.omit(ifelse(b==0,NA,a))
[1] 1 2 4
attr(,"na.action")
[1] 3
attr(,"class")
[1] "omit"

We can also use double negation我们也可以使用双重否定

a[!!b]
#[1] 1 2 4

data数据

a <- 1:4  
b <- c(1, 1, 0, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM