F.family
F.family

Reputation: 49

lapply functions inside each other does not work as expected

I have two lists and I must use for and if condition for my functions over these lists. I then decide to use lapply function. I used lapply function but my code becomes so difficult and do not work. How can I make my code work in an easy way. Is there a good way to do not use many lapply functions.

The idea of my code:

  1. First have some lists.
  2. These lists does not need to be all the same lengths or even all > 0.
  3. So, my code check each list. if it is > 0 or not.
  4. If it is > 0 then:

  5. check the values of the second list.

  6. If the values equal specific values then this values will changes to new values.

The last steps must applied to all the lists that I have.

Here is my code:

the function gave me NULL

nx <- list(1, 1) ## if my list  > 0 then check it
x.t <- list(c(2, 3, 4, 4), c(2, 4, 5, 6))  #the list to apply if statement on it. 

lapply(nx, function(x) if (x > 0) {
  do.t <-  lapply(x.t, function(x) { which(x %in% c(2, 7:10))})
  ##check the values of my list.

  lapply(nx, function(x){

  lapply(1:length(x), function(i){  for (j in 1:x[[i]]){ ## here I would like j from 1 to length of x where x is a list of two elements.

      if (x.t[[i]][do.t[[j]]] == 2) ## here I want to have a condition says that, if the element of each list is equal 2 then this element will have the value 2.5.
        x.t[[i]] <- 2.5
    }})})})

my function will includes many lists where the condition will be extend. For example,

    if (x.t[[i]][do.t[[j]]] == 2){
      x.t[[i]] <- 2.5
}else{ some condition}elese{other condtion}

and so on.

the result.

[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
NULL


[[1]][[2]]
[[1]][[2]][[1]]
NULL



[[2]]
[[2]][[1]]
[[2]][[1]][[1]]
NULL


[[2]][[2]]
[[2]][[2]][[1]]
NULL

My function is so complicated and hence I provide this example very similar to my original function.

Upvotes: 0

Views: 177

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

As a general function maybe it's better to divide the code into parts, each one doing just one thing.
Note that the lapply passes entire vectors, the elements of the list x.t to the function. Then, complicated loops through the elements of a vector, processing one at a time.

complicated <- function(x){
    for(i in seq_along(x)){
        if(x[i] > 0){
            if(x[i] == 2)
                x[i] <- 2.5
        }
    }
    x
}

x.t.2 <- lapply(x.t, function(x){
    x <- complicated(x)
    x
})

x.t.2
#[[1]]
#[1] 2.5 3.0 4.0 4.0
#
#[[2]]
#[1] 2.5 4.0 5.0 6.0

Upvotes: 1

Related Questions