r - Looping through elements of a list and then appending to a new list -
i've been trying write code allow me loop through items of list, each of vector of numeric values. elements of vector meets criterion, want append numbers new list contains vector of numeric values.
my dataset structured following:
col1 col2 col3 .... col29 -11 -10 -9 .... 15 -13 -12 -11 .... 14
i've tried following code 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) { # stuck here, code i've run gives me error. } } }
i want list that's structured pretty same original, keeping numbers greater or equal 0.
any appreciated.
i call data df
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 check whether dealing positive number , return either true
or false
. we'll use 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
Comments
Post a Comment