R 循环遍历列表的元素,然后追加到新列表

R 循环遍历列表的元素,然后追加到新列表,r,R,我一直在尝试编写代码,使我能够循环遍历列表中的项目,每个项目都是数值向量。对于向量的元素满足某个标准,那么我想将这些数字附加到一个新的列表中,该列表也包含一个数值向量 我的数据集的结构如下所示: Col1 Col2 Col3 .... Col29 -11 -10 -9 .... 15 -13 -12 -11 .... 14 到目前为止,我已经尝试了以下代码: new_list <- list() for(i in 1:length(time_list)) { f

我一直在尝试编写代码,使我能够循环遍历列表中的项目,每个项目都是数值向量。对于向量的元素满足某个标准,那么我想将这些数字附加到一个新的列表中,该列表也包含一个数值向量

我的数据集的结构如下所示:

Col1 Col2 Col3 .... Col29
-11   -10  -9  ....   15
-13   -12  -11 ....   14
到目前为止,我已经尝试了以下代码:

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.
    }
  }
}
我想要一个结构与原始列表几乎相同的列表,但只保留大于或等于0的数字

任何帮助都将不胜感激

我会给你的数据打电话

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)
}

从上面的陈述中,听起来您只想从列表中删除负值。如果是这样的话,那你为什么不试试这样的方法呢:

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

你错过了一次接近接近的机会。此外,虽然可能不会有问题,但使用seq_alongtime_list代替1:lengthtime_list。1:lengthtime_list[[i]]也一样。我刚刚解决了这个问题。它实际上在R中,只是在这里输入了一个错误:你有什么错误?嗨,肯。我每次尝试新列表时都会收到警告[I][j]你能使用dputtime\u列表吗?如果没有看到你的数据,很难确定问题出在哪里,肯。这很好,但我需要它是一个向量列表。我想另一张海报的解决方案正是我想要的。谢谢你做的一切。这太完美了。非常感谢。
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