about subsetting a dataframe in R

131 Views Asked by At

I would appreciate your suggestions on subsetting a data frame. Let's consider an example data frame df:

dd <- c(1,2,3)
rows <- c("A1","A2","A3")
columns <- c("B1","B2","B3")
numbers <- c(400, 500, 600)    
df <- dataframe(dd, rows, columns, numbers)

and a vector : test_rows <-c("A1","A3")

How could I subset the data frame df function of vector test_rows in such a way that only the row of data frame df (df$rows) that match the elements of test_rows ("A1" and "A3") are listed?

2

There are 2 best solutions below

4
On

Here is your answer:

df[df$rows %in% test_rows,]

btw, df is a name of a built in function in R so it is better not to use it as a name for variables.

0
On

Just in case your data set is very large and you want a faster solution here is the dplyr code to achieve the same result:

df %>% filter(rows %in% test_rows)