Home > OS >  How to delete certain rows in R within dataframe
How to delete certain rows in R within dataframe

Time:07-14

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"

I am trying following code and its not working

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

CodePudding user response:

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. Partial matching is misleading in your case, because 0 also shows up in for example, 60, and actually all marks. So you will not get rid of any rows. Use exact match: 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, ].

CodePudding user response:

If you would like to use str_detect, you should use the pattern ^0 like this:

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)

CodePudding user response:

Using base r method

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
  • Related