1

我正在尝试从包含某些植被类型的数据集中删除行。我想从我的未调查数据中删除那些在我的调查数据中没有找到植被类型的行。我找到了一种方法来做到这一点,但正在寻找一种单线方法。我目前正在这样做:

> setdiff(unsurveyed_1$VEGETATION, surveyed_1$VEGETATION)

它返回七种植被类型,然后我删除它们:

> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Acer rubrum- Nyssa sylvatica saturated forest alliance",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Acer rubrum/Quercus coccinea-Acer rubrum-Vaccinium corybosum-Vaccinium palladium",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Building",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Parking Lot",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Prunus serotina",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Typha (angustifolia, latifolia) - (Schoenoplectus spp.) Eastern Herbaceous Vegetation",]
> unsurveyed_1 <- unsurveyed_1[!unsurveyed_1$VEGETATION == "Water",]

我尝试了一些不同的选项,包括到目前为止收效甚微的子集,我认为这将是我最好的选择。我也在寻找与 intersect 类似的东西,但我假设它会有类似的答案。

编辑:除了使用@Cath 提供的代码之外,我还对其进行了编辑以得到相反的结果。

> unsurveyed_2 <- unsurveyed_2[unsurveyed_2$VEGETATION %in% setdiff(unsurveyed_2$VEGETATION, surveyed_1$VEGETATION), ]
4

1 回答 1

3

显而易见的是:

ID <- unsurveyed_1$VEGETATION %in% unique(surveyed_1$VEGETATION)
unsurveyed1 <- unsurveyed1[ID,]

您使用逻辑向量ID作为行索引来选择要保留的行。对可以在其中找到的每一行ID都有一个值,否则。如果您有大量数据并且没有太多不同的植被类型,则使用唯一值只会提高性能。TRUEunsurveyed1$VEGETATIONsurveyed1$VEGETATIONFALSEsurveyed1$VEGETATION

因此,无需使用任何东西,setdiff()而且更不需要将每个结果复制到新行中。在 R 中工作时,请开始考虑临时对象。这将使您的编程生活变得更加轻松。

编辑:这正是@Cath 在他/她的单行评论中所做的。


如果您坚持使用setdiff(),那么这将减少打字工作:

thediff <- setdiff(unsurveyed_1$VEGETATION, surveyed_1$VEGETATION)
ID <- unsurveyed_1$VEGETATION %in% thediff
unsurveyed1 <- unsurveyed1[!ID,]

请注意,您必须ID使用 NOT ( !) 运算符反转向量,以删除所有未测量的植被与 中的值匹配的线thediff

setdiff()附带说明:和的内部代码%in%几乎完全相同。不同之处在于setdiff()返回在第二个向量中未找到的实际值,并%in%返回一个逻辑向量,说明FALSE是否在第二个向量中未找到该值。

于 2016-02-16T13:43:35.853 回答