user9798936
user9798936

Reputation:

How to use if statment with a list in R

I have a list of two items. I would like to set a condition using the if statement. The condition needs to contain the all statement as well.

In other words,

Suppose I have the following list:

library(VineCopula)
x <- BiCop(0,0)
y <- BiCop(0,0)
z <- list(x, y)

I would like to have a condition that said that if all the z[[i]]$tau less or greater than a specific value, then z must be set to zero.

Here is my code (kindly note that my list can have any length. That is, the length is not fixed. Here, I fixed the length to two elements only, but my real data needs to be more than 2.):

     for (i in seq_len(m)){
  if (all( 0 <= z[[i]]$tau =< 0.15))
    z <- 0
}

How to do this in R?

Upvotes: 2

Views: 1196

Answers (1)

akrun
akrun

Reputation: 887118

Extract the list element, wrap with all on the logical condition to return a single TRUE/FALSE, use that in if, loop over the 'z' and assign the tau elements to 0

tau1 <- sapply(z, "[[", "tau") 
i1 <- all(tau1 >= 0 & tau1 <= 0.15)
if(i1) {
   z <- lapply(z, function(x) {x$tau <- 0; x})
}

The syntax 0 <= z[[i]]$tau =< 0.15 seems to mathematical which is not a correct R syntax as we need to have two expressions joined with &. Also, as we are doing the check on all the list elements, we may need to do this in two for loop (if for loop is used) - first one to check if all meets the condition and second to do the assignment (in case the first returned TRUE) i.e.

i1 <- TRUE
# // first loop
for(i in seq_along(z)) {
     i1 <- i1 & z[[i]]$tau >= 0 & z[[i]]$tau <= 0.15
}
# // second loop
if(i1) {
   for(i in seq_along(z)) {
        z[[i]]$tau <- 0
     }
}

Upvotes: 2

Related Questions