Reputation: 3394
data=data.frame("grade"=c(1, 2, 3, 1, 2, 3),
"class"=c('a', 'a', 'a', 'b', 'b', 'b'),
"size"=c(1, 1, 2, 2, 2, 1),
"var"=c('q33', 'q35', 'q39', 'q33', 'q35', 'q39'),
"score"=c(5, 8, 7, 3, 7, 5))
If suppose I wish to subset data to exclude any row with 'var' ending in '5' how can I do this? Hopeful output:
data1=data.frame("grade"=c(1, 3, 1, 3),
"class"=c('a', 'a', 'b', 'b'),
"size"=c(1,2, 2, 1),
"var"=c('q33', 'q39', 'q33', 'q39'),
"score"=c(5, 7, 3, 5))
Upvotes: 1
Views: 1118
Reputation: 389175
As @Frank mentioned we can use built-in endsWith
which requires a character input.
subset(data, !endsWith(var, "5"))
# grade class size var score
#1 1 a 1 q33 5
#3 3 a 2 q39 7
#4 1 b 2 q33 3
#6 3 b 1 q39 5
data
data <- data.frame(grade=c(1, 2, 3, 1, 2, 3),
class=c('a', 'a', 'a', 'b', 'b', 'b'),
size=c(1, 1, 2, 2, 2, 1),
var=c('q33', 'q35', 'q39', 'q33', 'q35', 'q39'),
score=c(5, 8, 7, 3, 7, 5), stringsAsFactors = FALSE)
Upvotes: 0
Reputation: 887691
We can use grepl
with $
to specify the end of string
subset(data, !grepl('5$', var))
# grade class size var score
#1 1 a 1 q33 5
#3 3 a 2 q39 7
#4 1 b 2 q33 3
#6 3 b 1 q39 5
If we need to check for both first and last, use ^
to specify the start
subset(data, !grepl('^5|5$', var))
In this case, the start character is not digit, if we want to check the first occurrence of digit
subset(data, !grepl('\\D+5|5$', var))
Upvotes: 3