Reputation: 360
c <- data.frame("c1"=c(78,89,0),"c2"=c(89,89,34),"c3"=c(56,0,4))
row.names(c) <- c("zebra","fish","zucchini")
c <- rm(grep("z",rownames(c))) ??
hopefully short question, short answer: What is wrong with the above code? It says me "must contain names or character strings". How do I remove all rows that contain z in their rownames. In this reprex only fish is left.
Thank you sooo much
Upvotes: 0
Views: 2707
Reputation: 269644
1) grepl There are several problems:
c
is not a good name to use given the ubiquitous use of the c
function in R so we use cc
insteadgrepl
with an l
on the end instead of grep
in order to get a logical vector result and then use ! to negate it.rm
is used to remove objects from the workspace, not to remove rows from a data frame, so we use subscripts instead. No packages are used.
cc[!grepl("z", rownames(cc)), ]
## c1 c2 c3
## fish 89 89 0
2) grep As an alternative it would also be possible to use grep
with the invert=TRUE
argument:
cc[grep("z", rownames(cc), invert = TRUE), ]
## c1 c2 c3
## fish 89 89 0
3) substr In the example the z
character always appears as the first character so if this is the case in general we could alternately use:
cc[substr(rownames(cc), 1, 1) != "z", ]
## c1 c2 c3
## fish 89 89 0
3a) startsWith Another approach if z
must be the first character is:
cc[!startsWith(rownames(cc), "z"), ]
## c1 c2 c3
## fish 89 89 0
cc <- data.frame(c1 = c(78, 89, 0), c2 = c(89, 89, 34), c3 = c(56, 0, 4))
row.names(cc) <- c("zebra", "fish", "zucchini")
Upvotes: 3
Reputation: 784
Your example uses deprecated properties. I have edited it somewhat.
/Edit: Now I'm understanding that you wish to remove those rows, see the following example:
c <- tibble("c1"=c(78,89,0),"c2"=c(89,89,34),"c3"=c(56,0,4),
"rownames"=c("zebra","fish","zucchini")) %>%
column_to_rownames("rownames")
c[!grepl("i", rownames(c)),]
c1 c2 c3
zebra 78 89 56
Also, as pointed out before, c should not be an object name, as it also is a central function in R.
Upvotes: -1
Reputation: 2770
Rm removes objects. You are trying to filter on row.
c <- data.frame("c1"=c(78,89,0),"c2"=c(89,89,34),"c3"=c(56,0,4))
row.names(c) <- c("zebra","fish","zucchini")
print( c )
c[ !grepl("z",rownames(c)) , ]
Upvotes: 1