【问题标题】:是否有R函数可以删除数据框中的元素[重复]
【发布时间】:2022-01-23 16:24:48
【问题描述】:

如果在 Name 列中找不到某个单词,我正在寻找一种方法来删除数据框中的元素(删除整行)。在我的例子中,该元素的颜色类似于red,blue,green

数据集如下所示:

Name|Classification
A red apple | Fruit
A banana | Fruit
A blue carrot | Vegetable

我使用以下代码循环遍历数据框并检查颜色是否在名称列的字符串中。目前只看红色以使其工作。

for(i in 1:length(nsl)){
if(!grepl("red",nsl[[1:i]],fixed=TRUE)){
nsl[[1:i]] <- " " #This is where I want to delete the item or set it to empty (so later on I can filter all empty out)
}
}

但我不知道它是如何在具有两列/维度的数据框中完成的。我找到的所有互联网教程都告诉我使用nsl[-index_element_here],但这会删除Classification 列。他们将其用于一维列表的示例。或者告诉我使用%in%,我认为这不是我想要的。

预期的最终结果是一个数据框,其中只有带颜色的水果和蔬菜。非颜色被删除。

【问题讨论】:

  • 它不是向量。这是一个数据框。一个向量只有一维
  • @Sotos 感谢您的澄清。我总是把这些概念搞砸。

标签: r


【解决方案1】:

不需要循环:

nsl <- read.table(text = "Name|Classification
'A red apple' | Fruit
'A banana' | Fruit
'A blue carrot' | Vegetable
", header = TRUE, sep = "|")

nsl[!grepl("red", nsl$Name, fixed = TRUE), ]
#>             Name Classification
#> 2      A banana           Fruit
#> 3 A blue carrot       Vegetable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-26
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2020-09-15
    • 1970-01-01
    • 2019-12-24
    相关资源
    最近更新 更多