0

I have been able to use which() to extract data from two individual columns based on a given criteria:

# cars with 6 cylinders
cyl_6 <- which(mtcars$cyl == 6)

# cars with 4 gears
gear_4 <- which(mtcars$gear == 4)

Respectively these return:

> cyl_6
[1]  1  2  4  6 10 11 30
> gear_4
[1]  1  2  3  8  9 10 11 18 19 20 26 32

How can I compare these two objects to get the common values into a new object? I'm expecting the outcome to be:

> cyl_6_gear_4
[1] 1 2 10 11
MJL
  • 161
  • 7
  • 1
    Does this answer your question? [How to find common elements from multiple vectors?](https://stackoverflow.com/questions/3695677/how-to-find-common-elements-from-multiple-vectors) – Fateta Apr 21 '21 at 07:41
  • Yes, thank you!.. I was searching 'objects' not 'vectors'. Still kinda new to this. – MJL Apr 22 '21 at 00:44

2 Answers2

2

If you want to retain possible duplicates, you can use %in%

subset(cyl_6, cyl_6 %in% gear_4)

Otherwise, a simpler one might be intersect

intersect(cyl_6, gear_4)
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

intersect() will get what you need

intersect(cyl_6, gear_4)
[1]  1  2 10 11
sammy
  • 427
  • 1
  • 3
  • 14