Search code examples
rsubsetsegment

Subset data.frame based on a column that matches a separate vector


once again stumped here.

I have a data.frame of 4 columns:

Col1      Col2      Col3      Col4
1         1.lsm     0.43      0.34
2         1.lsm     0.47      0.30
3         1.lsm     0.27      0.85
1         2.lsm     0.35      0.55
2         2.lsm     0.71      0.46
3         2.lsm     0.53      0.37
4         2.lsm     0.63      0.34

Col1 is the cell number for cells that have been tracked over time.

I have a vector containing integers pertaining to which cells I want to keep:

keep=c(3, 4)

Now, I want to use the vector "keep" to decide which rows of the data.frame are kept and output a new data.frame with all columns but keep only the relevant rows.

I.e. the ideal output here would be:

Col1      Col2      Col3      Col4
3         1.lsm     0.27      0.85
3         2.lsm     0.53      0.37
4         2.lsm     0.63      0.34

Solution

  • You can try this

     df[df$Col1 %in% keep, ]
     #   Col1  Col2 Col3 Col4
     # 3    3 1.lsm 0.27 0.85
     # 6    3 2.lsm 0.53 0.37
     # 7    4 2.lsm 0.63 0.34