2014-12-27 70 views
0

我试图创建一个新的数据集,从ds2中删除一些行(通过与数据集ds1的比较)。我写了一个函数,应该这样做:向R中的数据集追加行

compare<-function(ds1,ds2){ 
for(i in 1:length(ds1$long)){ 
    for(j in 1:length(ds2$long)){ 
     if(ds1$long[i]<(ds2$long[j]+500) & ds1$long[i]>(ds2$long[j]-500)){ 
      if(ds1$lat[i]<(ds2$lat[j]+500) & ds1$lat[i]>(ds2$lat[j]-500)){ 
       ds3<-data.frame(merge(ds2[j,],ds3)) 
      } 
     } 
    } 
} 
return(ds3) 
} 

DS3是我想要返回的数据集,它应该由原始数据集DS2的符合上述条件的行形成。 我的功能给我一个错误:

Error in as.data.frame(y) : 
argument "y" is not specified and has not a definite value 

是“合并()”的权利建立这样一个数据集,追加行DS3功能? 如果不是,哪个是正确的功能呢?

谢谢大家提前

编辑:我修改了功能,感谢您的提示,使用

ds3<-data.frame() 
ds3<-rbind(ds3,ds2[j,]) 

,而不是

ds3<-data.frame(merge(ds2[j,],ds3)) 

现在我得到这个错误:

Errore in rbind(ds3, ds2[j, ]) : 
no method for coercing this S4 class to a vector 

如果我使用rbind(),我可以使用SpatialPoints吗? (包含在我的数据集中的数据是空间点)

Edit2:我有2个数据集,一个有330行(不规则网格上的点,ds1),一个有150000行(常规网格上的点,ds2)。我想计算第一个数据集中的变量与第二个数据集中的变量之间的相关性。为了做到这一点,我想将第二个数据集“缩小”到第一个数据集的维度,只保存两个数据集中具有相同坐标(或准)的点。

+1

尝试使用'rbind'而不是'merge' – LyzandeR 2014-12-27 15:05:05

+1

初始化'ds3'并使用'rbind'。 – Khashaa 2014-12-27 15:05:36

+0

第1步:子集ds1用'['by conditions第2步'rbind'不应该有它的外观所需的任何循环。请用数据示例和期望的结果澄清问题 – 2014-12-27 16:59:42

回答

0

没有一个小例子,这个没有测试,但如果你是幸福的for循环的性能,那么这可能是你正在尝试什么:

compare<-function(ds1,ds2){ 
for(i in 1:length(ds1$long)){ 
    for(j in i:length(ds2$long)){ # I think starting at 1 will give twice as many hits 
     if(ds1$long[i]<(ds2$long[j]+500) & ds1$long[i]>(ds2$long[j]-500)){ 
      if(ds1$lat[i]<(ds2$lat[j]+500) & ds1$lat[i]>(ds2$lat[j]-500)){ 
       if(length(d3)) { # check to see if d3 exists or not 
       ds3<-rbind(ds3, ds2[,j]) } else { # append as the next row 
       d3 <- ds2[ ,j] } # should only get executed once 
      } 
     } 
    } 
} 
return(ds3) 
} 

我试图避免重新测试的额外开销对于j,我匹配你已经有过i,j匹配的地方。再次,我不能确定这是否合适,因为问题描述仍然不完全清楚。

+0

签署你的答案是正确的,因为耐心写一些代码并阅读问题。我又遇到了一些问题,但你的回答很有用。 – Eugen 2015-01-09 09:30:08