Home > other >  Making a list in R which has only 1 value in each index
Making a list in R which has only 1 value in each index

Time:04-02

so im trying to make a list where each index ( listname[[i]]) has only 1 value. when I assign each value manually it works but when i try assigning in a for loop it puts all of the list in index 1 (and not assigning the values i want, it assigns NULL) clarify: I DONT want a nested list. i want a normal list with length(force1[[2]]) and in each index to assign 0 or 1 according to a condition

  • force1 is a list of 2. index 1 has a string list and index 2 has a numeric list

code for testing:

temp_bool <- FALSE
birth_binary <- list()
birth_binary[[length(force1[[2]])]] <- 1



for (i in seq_len(length((force1[[2]])))){
  temp_bool <- as.integer(force1[[2]][i]) < as.integer(45)
  if (temp_bool == TRUE){
    append(birth_binary,list('1'))
  }
    else{
      append(birth_binary,list('0'))
    }


  }
temp_bool <- TRUE
if (temp_bool == TRUE){
  birth_binary[[5]] <- 90

[force 1][1]

manual: result of manual:

using "for" loop: result of "for" loop

I have tried using append() with both a value to add and a vector to add. also tried using the assignment <- to the i'th index.

CodePudding user response:

Instead of creating a loop, extract the second element of 'force1' list (force1[[2]]), check whether it is less than 45 (< 45), convert the logical to binary ( or as.integer) and convert the binary vector to list with as.list and assign to a new object 'birth_binary'

birth_binary <- as.list( (force1[[2]] < 45))
  • Related