Learning_R
Learning_R

Reputation: 659

R - How to choose rows based on values in column

I have a dataframe, data, shown below:

head(data)
      code       x     y        z        new
1   123456       1     2        0     654321 
2   999999       2     3        0     543210
3   000998       3     4        0     887765
4   106813       4     6        0         NA
5   222345       5     6        0     564738
6   106815       6     5        0         NA
7   887765       7     1        1     000998

I am trying to make sure that the linked data is kept. For example, if i make a new matrix by subsetting the data so that it only keeps rows with x < 4:

data2 <- subset(data,x<4)
data2
    Code x y z    new
1 123456 1 2 0 654321
2 999999 2 3 0 543210
3 000998 3 4 0 887765

I would then like to add any rows in which the new value for a row in the subsetted data (data2) is equal to the code value of a row that was in the original data, like so:

data3
    Code x y z    new
1 123456 1 2 0 654321
2 999999 2 3 0 543210
3 000998 3 4 0 887765
4 887765 7 1 1 000998

Upvotes: 2

Views: 218

Answers (1)

Jacob H
Jacob H

Reputation: 4513

This is not the prettiest but it works

rbind(data2, merge(data, data2[,"new", drop = FALSE], by.x = "code", by.y = "new"))

Upvotes: 2

Related Questions