user122514
user122514

Reputation: 407

Looping through elements of a list and then appending to a new list

I've been trying to write code that would allow me to loop through the items of the list, each of which is a vector of numeric values. For elements of the vector meets a certain criterion, then I want to append those numbers to a new list that also contains a vector of numeric values.

My dataset is structured like the following:

Col1 Col2 Col3 .... Col29
-11   -10  -9  ....   15
-13   -12  -11 ....   14

I've tried the following code thus far:

new_list <- list()
for(i in 1:length(time_list)) {
  for(j in 1:length(time_list[[i]]) {
    if(!is.na(time_list[[i]][j]) & time_list[[i]][j] >= 0) {
      # I am stuck here, as all the code I've run gives me an error.
    }
  }
}

I want a list that's structured pretty much the same as the original, but keeping only numbers greater than or equal to 0.

Any help would be greatly appreciated.

Upvotes: 0

Views: 35

Answers (2)

Katie
Katie

Reputation: 362

From your above statement, it sounds like you only want to delete negative values from your list. If that is the case, then why don't you try something like this:

row1 <- c(-11,-10,-9,-7,0,3,15)
row2 <- c(-13,-12,-11,2,0,-7,14)

time_list <- rbind(row1,row2)
> time_list
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
row1  -11  -10   -9   -7    0    3   15
row2  -13  -12  -11    2    0   -7   14

time_list[time_list<0] <- NA
> time_list
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
row1   NA   NA   NA   NA    0    3   15
row2   NA   NA   NA    2    0   NA   14

new_time_list <- time_list[,colSums(is.na(time_list))<nrow(time_list)]
> new_time_list
     [,1] [,2] [,3] [,4]
row1   NA    0    3   15
row2    2    0   NA   14

Upvotes: 0

KenHBS
KenHBS

Reputation: 7164

I will call your data df like

df <- structure(list(Time_1 = -13L, Time_2 = -12L, Time_3 = -11L, Time_4 = -10L, 
        Time_5 = -9L, Time_6 = -8L, Time_7 = -7L, Time_8 = -6L, Time_9 = -5L, 
        Time_10 = -4L, Time_11 = -3L, Time_12 = -2L, Time_13 = -1L, Time_14 = 0L, 
        Time_15 = 1L))

is.pos <- function(x){
  (!is.na(x)) & (x >= 0)
}

The function will check whether we are dealing with a positive number and return either TRUE or FALSE. We'll use this for indexing:

is.pos(df)
# Time_1  Time_2  Time_3  Time_4  Time_5  Time_6  Time_7  Time_8  Time_9 Time_10 
# FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE 
# Time_11 Time_12 Time_13 Time_14 Time_15 
# FALSE   FALSE   FALSE    TRUE    TRUE 

df[is.pos(df)]
# $Time_14
# [1] 0
# 
# $Time_15
# [1] 1

Upvotes: 1

Related Questions