Home > front end >  How to replace values with a condition in R?
How to replace values with a condition in R?

Time:09-08

With a vector dr, I need to check if there are more than 5 values in dr > 0. If so keep it as as. If not return the vector with replacing all values with 0.

dr <- c(1,5,3,2,0,2,0,2,0,0,0,2,0)

will be

dr <- c(1,5,3,2,0,2,0,2,0,0,0,2,0)

but

dr <- c(1,0,0,0,0,2,0,0,0,0,0,2,0)

will be

dr <- c(0,0,0,0,0,0,0,0,0,0,0,0,0)

CodePudding user response:

You could use replace() to replace the whole vector with zeros if there are less than 5 positive values in it.

fun <- function(vec) replace(vec, sum(vec > 0) < 5, 0)

sum(vec > 0) < 5 returns a single logical value (either TRUE or FALSE) and it'll recycle to the same length as vec.

Test
dr1 <- c(1,5,3,2,0,2,0,2,0,0,0,2,0)
dr2 <- c(1,0,0,0,0,2,0,0,0,0,0,2,0)

fun(dr1)
# [1] 1 5 3 2 0 2 0 2 0 0 0 2 0

fun(dr2)
# [1] 0 0 0 0 0 0 0 0 0 0 0 0 0

CodePudding user response:

Use if and else:

f <- function(vec) if(sum(vec > 0) >= 5) vec else rep(0, length(vec))

Also works with integer:

f <- function(vec) if(sum(vec > 0) >= 5) vec else integer(length(vec))

Operationalization:

> dr <- c(1,5,3,2,0,2,0,2,0,0,0,2,0)
> f(dr)
#> [1] 1 5 3 2 0 2 0 2 0 0 0 2 0

> dr <- c(1,0,0,0,0,2,0,0,0,0,0,2,0)
> f(dr)
#> [1] 0 0 0 0 0 0 0 0 0 0 0 0 0

CodePudding user response:

Does this work:

r
 [1] 1 5 3 2 0 2 0 2 0 0 0 2 0
v
 [1] 1 0 0 0 0 2 0 0 0 0 0 2 0
vector_0 <- function(ip_vec){
      if(isTRUE(rle(ip_vec)[[2]][which(rle(ip_vec)[[1]] == 5)] == 0)) {ip_vec * 0}
      else {ip_vec}
}
vector_0(r)
 [1] 1 5 3 2 0 2 0 2 0 0 0 2 0
vector_0(v)
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0
  •  Tags:  
  • r
  • Related