imran p
imran p

Reputation: 332

Filter rows based on condition

below is the dataframe df. Can we filter it based on conditions. Like, if there are charaters in 3rd col and Null in 3rd col, those should be filtered

  row col value
1   1   0    ID
2   1   1    12
3   1   2    12
4   1   3     4
5   1   4   

Expected output

  row col value
2   1   1    12
3   1   2    12
4   1   3     4

Upvotes: 0

Views: 58

Answers (3)

akrun
akrun

Reputation: 886938

It is also easier to convert to numeric and subset on the non NA elements

subset(df, !is.na(as.numeric(value)))

Or with filter

library(dplyr)
library(stringr)
df %>%
   filter(str_detect(value, "^[0-9.]+$"))

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388807

You can use :

subset(df, !(grepl("[A-Za-z]",value) | value == ''))

#  row col value
#2   1   1    12
#3   1   2    12
#4   1   3     4

This removes rows where characters ([A-Za-z]) OR empty values are present.

Upvotes: 2

arg0naut91
arg0naut91

Reputation: 14764

We can perhaps just keep all the rows with digits in value column:

df[grepl('\\d', df$value),]

Output:

  row col value
2   1   1    12
3   1   2    12
4   1   3     4

Upvotes: 4

Related Questions