There are a couple of problems with your code. Firstly, you have a "#" in one of your column names, which means you need to quote the column name; otherwise R will think you are starting a comment and will ignore the rest of the line. So your line
Data1 <- Data[- grep("",Data$Item# || "12345" Data$Charge)
will be interpreted as
Data1 <- Data[- grep("",Data$Item
by R, which will give you a syntax error.
In any case, this syntax isn't how grep
works. If you want to test columns based on multiple regexes, you can use multiple grepl
functions, each of which returns a logical vector, and just combine these. However, you can't use grep
or grepl
with an empty string, since every string contains an empty string! You can test for an empty string just by using == ""
When subsetting by rows, you need a comma after the conditions and the closing bracket, as @dcarlson pointed out.
Lastly, you should use &
if you want to find the cases where only both conditions apply rather than ||
.
Therefore your code should be:
Data1 <- Data[-which(Data$'Item#' == "" & grepl("12345", Data$Charge)),]
Data1
#> Item# Charge
#> 1 50 0
#> 2 61 12345
#> 4 43 0
#> 5 2521
#> 6 7 12345
I believe this matches your expected output.
Data used
df <- structure(list(`Item#` = c("50", "61", "", "43", "", "7"), Charge = c("0",
"12345", "12345", "0", "2521", "12345")), row.names = c(NA, -6L
), class = "data.frame")