I think the error in the code example you gave could be coming from a misplaced bracket in your second for statement, which should read for (j in ...) instead of for j in (...).
There are a number of ways to do this, but the simplest is probably just use "base R" subsetting.
First, I'll construct some data for the example:
dt1 <- data.frame(
v1 = c(4, 5, 9, 14, 7, 1),
v2 = c(12, 9, 17, 4, 2, 1)
)
dt2 <- data.frame(
v3 = c(4, 0, 1, 10, 7, 1),
v4 = c("a", "f", "s", "g", "w", "z")
)
Now, we use subsetting. R lets you subset a data frame by entering the row and column indexes into [] following the name of the data object, with the first space being for the rows, and the second for columns. So df1[1,2] returns the cell in the first row of the second column. If you leave one of these inputs blank, then R assumes you want every row (or column) that matches the other row/column condition provided. With this, we can do more complex subsetting:
dt3 <- dt2[dt1$v1 %in% dt2$v3, ]
Here, %in% is returning values of dt$v1 that are "in" dt2$v3, and since the columns input is blank, it returns all columns of the rows of dt2 that match the row condition. So we're creating dt3, which is a subsetting dt2. This gives you:
> dt3
v1 v2
1 4 12
5 7 2
6 1 1