Rnovice
Rnovice

Reputation: 79

Remove rows based on decimal places in column

I have a date frame that looks something like this:

     A  B      C   D

     1  1.0    2   4 

     2  3.1    2   3

     3  4.01   3   3

     4  5.00   4   5

     5  2.003  3   9

I want to delete rows where column B has numeric values other than 0 after the decimal. In the example above, this will leave me with rows 1 and 4. How do I go about this?

Upvotes: 0

Views: 661

Answers (4)

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

A regex solution in base R:

df[-which(grepl("\\.[0-9]*[1-9]$", df$B)),]
  A   B C
2 2   1 2
5 5 357 3

A regex solution in dplyr:

library(dplyr)
df %>%
  filter(!grepl("\\.[0-9]*[1-9]$", B))

Data:

df <- data.frame(
  A = 1:5,
  B = c(1.2, 1.0, 1.00004, 2.806, 357.0),
  C = c(2,2,3,4,3)
)

Upvotes: 0

akrun
akrun

Reputation: 887078

We can also use

subset(df, B == as.integer(B))

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101257

Try subset like below

subset(df, B == floor(B))
subset(df, B == ceiling(B))
subset(df, B == round(B))
subset(df, B == trunc(B))

Upvotes: 0

Lennyy
Lennyy

Reputation: 6132

Assuming your dataframe is called df:

df[as.integer(df$B) == as.numeric(df$B),]

Upvotes: 0

Related Questions