如何过滤以 .0 或 .5 结尾的数字?
how to filter numbers that end with .0 or .5?
我正在尝试过滤掉所有包含不以 $.0、$.00、$.50 或 $.5 结尾的票价的数据
票价栏应始终以 $.0, $.00, $.50, $.5
结尾
我的数据如下所示:
df =
|date |id |fare
1|2018-11-25|12345|5.50
2|2018-11-26|12345|2.0
3|2018-11-26|12355|2.61
4|2018-11-27|12345|12.60
5|2018-11-27|12348|22.65
我尝试使用 grepl 函数,但它只是解决了我的问题。它包含我想要的内容,但缺少很多我期望存在的数据。
df[grepl("\.(?:.00$|.0$|.50$|.5$)$",df$fare), ]
我想创建一个包含行 3:5
的新 df
dfgood =
|date |id |fare
3|2018-11-26|12355|2.61
4|2018-11-27|12345|12.60
5|2018-11-27|12348|22.65
这个regex
应该可以做到
# If stored as character
df[!grepl('\.5$|\.0$|\.00$|\.50$', df$fare, perl = TRUE),]
# Else
df[!grepl('\.5$|\.0$|\.00$|\.50$', format(round(df$fare, 2), nsmall = 1), perl = TRUE),]
使用基数 r 的解决方案
##create some basic data
df = data.frame(date = c(1,2,3,4,5),
id = c(12345,12345,12355,12345,12348),
fare = c(5.5,2,2.61,12.60,22.65))
df[which(!(df$fare %% 1) %in% c(0.5,0)),]
好了:
library(dplyr)
dfgood <- df %>% filter((100*fare)%%50!=0)
我正在尝试过滤掉所有包含不以 $.0、$.00、$.50 或 $.5 结尾的票价的数据
票价栏应始终以 $.0, $.00, $.50, $.5
我的数据如下所示:
df =
|date |id |fare
1|2018-11-25|12345|5.50
2|2018-11-26|12345|2.0
3|2018-11-26|12355|2.61
4|2018-11-27|12345|12.60
5|2018-11-27|12348|22.65
我尝试使用 grepl 函数,但它只是解决了我的问题。它包含我想要的内容,但缺少很多我期望存在的数据。
df[grepl("\.(?:.00$|.0$|.50$|.5$)$",df$fare), ]
我想创建一个包含行 3:5
的新 dfdfgood =
|date |id |fare
3|2018-11-26|12355|2.61
4|2018-11-27|12345|12.60
5|2018-11-27|12348|22.65
这个regex
应该可以做到
# If stored as character
df[!grepl('\.5$|\.0$|\.00$|\.50$', df$fare, perl = TRUE),]
# Else
df[!grepl('\.5$|\.0$|\.00$|\.50$', format(round(df$fare, 2), nsmall = 1), perl = TRUE),]
使用基数 r 的解决方案
##create some basic data
df = data.frame(date = c(1,2,3,4,5),
id = c(12345,12345,12355,12345,12348),
fare = c(5.5,2,2.61,12.60,22.65))
df[which(!(df$fare %% 1) %in% c(0.5,0)),]
好了:
library(dplyr)
dfgood <- df %>% filter((100*fare)%%50!=0)