Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R-按向量值列出数据帧的子集_R_List_Loops_Spatial - Fatal编程技术网

R-按向量值列出数据帧的子集

R-按向量值列出数据帧的子集,r,list,loops,spatial,R,List,Loops,Spatial,我有一个SpatialLinesDataFrames列表,并希望在比较数值向量中的值的基础上对列表进行子集 具体来说,我想删除在data.frame的特定列('lineID')的向量中包含一个值的列表元素。可复制示例: #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 <

我有一个
SpatialLinesDataFrames
列表,并希望在比较数值向量中的值的基础上对列表进行子集

具体来说,我想删除在data.frame的特定列('lineID')的向量中包含一个值的列表元素。可复制示例:

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

sldfl <- list()
sldfl[[1]] <- Sldf[1,]
sldfl[[2]] <- Sldf[2,]
sldfl[[3]] <- Sldf[3,]
sldfl[[4]] <- Sldf[4,]
sldfl[[5]] <- Sldf[5,]

#create numeric vector
m <- c(1,3,5,7,10)

#attempt to keep only list elements that are not equal to any 
#of the values contained in vector
final <- list()
for (i in 1:length(sldfl)) {
  for (j in 1:length(m)) {
    if (factor(sldfl[[i]]@data$lineID) != m[j]) {
      final[[i]] <- sldfl[[i]]
    }}}
#创建单个要素SpatialLineDataFrame的列表
图书馆(光栅)

l1基本上有两个向量,
ids
m

> ids
[1] 1 2 3 4 5
> m
[1]  1  3  5  7 10
基本上是这样的:

for(i in 1:length(ids)){
 for(j in 1:length(m)){
  if(i != m[j]){
    message("add ",i,j)
  }else{
    message("Not adding ",i,j)
  }
 }
}
运行它,您将看到它添加了很多元素,因为您正在使用
m
中的每个元素测试每个ID,并且
m
中至少有一个元素不在ID中,因此添加了一个(或多个)元素

你真正想要的是:

for(i in 1:length(ids)){

  if(!(i %in% m)){
    message("add ",i,j)
  }else{
    message("Not adding ",i,j)
  }
 }
其中打印:

Not adding 15
add 25
Not adding 35
add 45
Not adding 55
这将添加ID为2和4的元素,这些元素不在
m

或者,使用基本R
过滤器
函数,通过列表元素上的函数减少列表:

> Filter(function(L){!(L@data$lineID  %in% m)}, sldfl)
[[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 

因为对于sldfl列表中的每个多边形线条ID,
m
中至少存在一个不是完美ID的值。谢谢你的解答和解释