简体   繁体   English

如何删除数据框中R中的某些行

[英]How to delete certain rows in R within dataframe

my dataframe is like this我的数据框是这样的

class  subject  marks
1      bio      30
2      chem     40
3      bio      0
4      phy      60
5      maths    0
6      chem     0

I want to remove all rows from the column "marks" which have "0"我想从“标记”列中删除所有具有“0”的行

I am trying following code and its not working我正在尝试以下代码,但它不起作用

 df %>% 
  filter(!str_detect(marks, '0'))

I saw a deleted comment which explained a bit more.我看到一条已删除的评论,其中解释了更多。 I will try making it more concrete.我会尝试使它更具体。

Instead of partial matching using str_detect , you want exact match: marks != 0 .您需要完全匹配,而不是使用str_detect进行部分匹配: marks != 0 Partial matching is misleading in your case, because 0 also shows up in for example, 60, and actually all marks .在您的情况下,部分匹配具有误导性,因为 0 也出现在例如 60 中,实际上是所有marks So you will not get rid of any rows.所以你不会摆脱任何行。 Use exact match: df %>% filter(marks != 0) .使用完全匹配: df %>% filter(marks != 0)

Also, for a simple task like this, basis syntax is pretty good, like subset(df, marks != 0) or df[df$marks != 0, ] .此外,对于像这样的简单任务,基本语法非常好,例如subset(df, marks != 0)df[df$marks != 0, ]

If you would like to use str_detect , you should use the pattern ^0 like this:如果你想使用str_detect ,你应该像这样使用模式^0

df <- read.table(text="class  subject  marks
1      bio      30
2      chem     40
3      bio      0
4      phy      60
5      maths    0
6      chem     0", header = TRUE)

library(dplyr)
library(stringr)
df %>%
  filter(!str_detect(marks, "^0"))
#>   class subject marks
#> 1     1     bio    30
#> 2     2    chem    40
#> 3     4     phy    60

Created on 2022-07-14 by the reprex package (v2.0.1)reprex 包于 2022-07-14 创建 (v2.0.1)

Using base r method使用 base r 方法

a = read.table(text='class  subject  marks
1      bio      30
2      chem     40
3      bio      0
4      phy      60
5      maths    0
6      chem     0',header=T)

a=a[!a$marks==0,]

output:输出:

> a
  class subject marks
1     1     bio    30
2     2    chem    40
4     4     phy    60

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM