Select a subset of the data frame using unique identifiers

Suppose I have a data frame like this:

df <- data.frame (id = c("a", "b", "a", "c", "e", "d", "e"), n=1:7) 

and a vector with the same identifiers:

 v <- c("a", "b") 

How can I select data rows that match identifiers in v? I can not use the id column for the names of the growths, because they are not unique. When I try this, I get:

  rownames(df) <- df[["id"]] Error in `row.names<-.data.frame`(`*tmp*`, value = c(1L, 2L, 1L, 3L, 5L, : duplicate 'row.names' are not allowed In addition: Warning message: non-unique values when setting 'row.names': 'a', 'e' 
+7
r selection
source share
2 answers

This should do what you want:

 ndx = which(df$id %in% v) df[ndx,] 
+11
source share

Using

 df[df$id %in% v,] 
+15
source share

All Articles