从数值向量中基于值的 SpatialLinesDataFrames 列表中删除元素

remove elements from list of SpatialLinesDataFrames based values in a numeric vector

我有一个 SpatialLinesDataFrame 对象列表,我想删除包含 data.frame 列的值等于简单数值向量中的值之一的列表项。我想重复这个过程,因为实际列表很大。这是一个简化的示例数据,其中的循环没有按照我的意愿执行:

#create list of single-feature SpatialLineDataFrame
library(raster)

l1 <- cbind(c(0,3), c(0,3))
l2 <- cbind(c(0, 13), c(0, 1))
l3 <- cbind(c(0, 24), c(0,22.5))
l4 <- cbind(c(0, 1), c(0,13))
l5 <- cbind(c(0, 6), c(0,6))
Sldf <- spLines(l1, l2, l3, l4, l5, attr=data.frame(lineID=1:5))
linel <- lapply(1:5, function(i) Sldf[i,])
#numeric vector
x <- c(1,3,5)

newlist <- list()
for (i in 1:length(linel)){
  if (linel[[i]]@data$lineID == x) {
    newlist[[i]] <- linel[[i]]
  }
}

我收到以下错误消息:

Warning message: 1: In if (linel[[i]]@data$lineID == x) { : the condition has length > 1 and only the first element will be used

但我想要的是从列表中删除 lineID == 1 或 3 或 5(只是巧合地与示例中的索引 # 相同)的列表元素,最后得到:

newlist

[[1]]
class       : SpatialLinesDataFrame 
features    : 1 
extent      : 0, 13, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
variables   : 1
names       : lineID 
value       :      2 

[[2]]
class       : SpatialLinesDataFrame 
features    : 1 
extent      : 0, 13, 0, 1  (xmin, xmax, ymin, ymax)
coord. ref. : NA 
variables   : 1
names       : lineID 
value       :      4

您可以使用基数 R 中的 sapply 并从每个 linel 中提取 lineID,然后仅保留 x 中不存在的那些。

linel[!sapply(linel, function(data) data$lineID) %in% x]


#[[1]]
#class       : SpatialLinesDataFrame 
#features    : 1 
#extent      : 0, 13, 0, 1  (xmin, xmax, ymin, ymax)
#coord. ref. : NA 
#variables   : 1
#names       : lineID 
#value       :      2 

#[[2]]
#class       : SpatialLinesDataFrame 
#features    : 1 
#extent      : 0, 1, 0, 13  (xmin, xmax, ymin, ymax)
#coord. ref. : NA 
#variables   : 1
#names       : lineID 
#value       :      4 

更多使用purrr

的方法
purrr::discard(linel, ~ .$lineID %in% x)
purr::keep(linel, ~ ! .$lineID %in% x)

就您的 for 循环而言,您正在检查 == 的值。由于 x 是一个值向量,而不是使用 == 的单个值,因此会警告您它仅使用 x 中的第一个值。相反,你想用 %in% 来做,因为 x 中有多个值。但是,使用 %in% 会 return 一个 TRUE/FALSE 值的向量,然后您必须将其包装在 any 中。此外,即使在所有这些更改之后,代码正在做的是在 newlist 中的 x 中使用 lineID 保存这些列表元素,而不是从 linel 中删除它。所以你可能需要的是

newlist <- list()
j <- 1
for (i in 1:length(linel)){
   if (!any(linel[[i]]$lineID %in% x)) {
       newlist[[j]] <- linel[[i]]
       j = j + 1
    }
}

现在 newlist 就是您想要的列表。