r - 从R中的数据框中删除字符串
问题描述
我想从数据框中的第二列中删除带有字符串(完全匹配)的行:
输入:
>data
habitat species
wet species1_ind1
wet species1_ind1
dry species2_ind1
dry species2_ind1
dry species3_ind1
dry species3_ind1
...
所需的输出(删除了包含 species2_ind1 的行):
>new_data
habitat species
wet species1_ind1
wet species1_ind1
dry species3_ind1
dry species3_ind1
...
理想情况下,我想提供要从数据框中删除的字符串列表。
解决方案
你可以这样做%in%
data[!(data$species %in% c("species2_ind1")), ]
habitat species
1 wet species1_ind1
2 wet species1_ind1
5 dry species3_ind1
6 dry species3_ind1
详细信息:
这是选择species
不在列表中的行。数据既有行又有列。当您指定时data[x,y]
x 给出行而 y 给出列。data[x, ]
表示您已经用 x 指定了行,但取了所有列。上面的表达式采用所有列,但将行指定为!(data$species %in% c("species2_ind1"))
.
data$species %in% c("species2_ind1"))
给出 data$species 的值在列表中的那些行. 但那些是我们想要排除的,所以我们使用!
否定逻辑表达式并获取不在列表中 data$species
的行。
推荐阅读
- javascript - Javascript - 数组上的 flatMap 方法 - (flatMap 不是函数)
- c - 比较插入排序算法的先前数组元素
- sql-server - SQL Server 2016:更改数据仓库中的列顺序
- reactjs - 如何在较小的屏幕分辨率下重定向/路由到不同的链接,反之亦然?
- sql-server - 使用 T-SQL 提取 SQL 表中的 XML 数据
- java - Java Generic T 通过不同的参数类型参数化时出现奇怪的编译错误
- android - 使用 WorkManager 时出现 Java.util.concurrent.RejectedExecutionException
- algorithm - Max-Min 和 Min-Min 算法实现
- django - 图像保存在不同的表中
- wpf - 如何更改 Treeview 项目切换外观