You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言:如何从物种存在/缺失矩阵筛选指定列含1的行?

问题:筛选物种存在/缺失矩阵中至少含一个1的行

原始数据

物种存在/缺失矩阵结构如下:

coords.x  coords.y  1  2  3
Point 1            -69.07354 -15.76097  0 NA NA
Point 2            -69.91902 -15.86905  1  1 NA
Point 3            -69.90793 -15.79660  0  0 1
Point 4            -69.86849 -15.86500  0  0 NA
Point 5            -69.84020 -15.81637  1  0 NA

目标结果

需要提取列1、2、3中至少含一个1的行,移除无1的行,最终结果:

coords.x  coords.y  1  2  3
Point 2            -69.91902 -15.86905  1  1 NA
Point 3            -69.90793 -15.79660  0  0 1
Point 5            -69.84020 -15.81637  1  0 NA

尝试过程及问题

  1. 直接对矩阵使用filter:
SpeciesPoints <- filter(Species_Data,"1" = 0, "2" = 0,"3" = 0)

报错:

Error in UseMethod("filter") : 
  no applicable method for 'filter' applied to an object of class "c('matrix', 'array', 'double', 'numeric')"
  1. 转换为数据框后使用逻辑与筛选:
filter(Species_Data,"1" == 1 , "2" == 1,"3" == 1)

返回空数据框:

[1] coords.x coords.y 1        2        3       
<0 rows> (or 0-length row.names)
  1. 尝试逻辑或运算符:
filter(Species_Data,"1" == 1 | "2" == 1|"3" == 1)

未移除任何行,不符合预期。


解决方案

核心问题分析

  • dplyr::filter仅支持数据框/tbl对象,矩阵需先转数据框。
  • 列名为数字时,需用反引号`包裹(如`1`),而非字符串引号,否则会变成字面量比较(如"1" ==1永远为FALSE)。
  • 需处理NA:NA与数值比较会返回NA,需将其视为"无1"处理。

方法1:使用dplyr(推荐)

library(dplyr)

# 确保数据是数据框(如果原数据是矩阵)
Species_Data <- as.data.frame(Species_Data)

# 筛选逻辑:列1-3中至少有一个1,NA视为无1
SpeciesPoints <- Species_Data %>%
  filter(rowSums(select(., `1`:`3`) == 1, na.rm = TRUE) > 0)

解释:

  • select(., 1:3)提取物种列;
  • ==1生成布尔矩阵,标记值为1的位置;
  • rowSums(..., na.rm = TRUE)计算每行的1的数量(忽略NA);
  • 筛选行和>0的行,即至少含一个1的行。

方法2:Base R实现

# 转换为数据框(若需)
Species_Data <- as.data.frame(Species_Data)

# 提取物种列,将NA替换为0
species_cols <- Species_Data[, c("1", "2", "3")]
species_cols[is.na(species_cols)] <- 0

# 筛选至少含一个1的行
SpeciesPoints <- Species_Data[rowSums(species_cols == 1) > 0, ]

验证结果

运行上述代码后,SpeciesPoints将得到目标结果,仅保留Point2、Point3、Point5三行。


内容的提问来源于stack exchange,提问作者Birdman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:22:03