简体   繁体   中英

Filter a Data.frame based on Rownames

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

1) grepl There are several problems:

  • the test data in the question has errors so we use the one in the Note at the end
  • although not strictly wrong, c is not a good name to use given the ubiquitous use of the c function in R so we use cc instead
  • we use grepl 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

Note

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")

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)) , ] 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM