How to make the difference between two data.frames in R?

Asked

Viewed 254 times

2

I created two data.frames: the first data.frame that comes from an original basis and the second data.frame which originates from the first, but with the application of a filter.

Example:

print(DADOS)

    CODE  A  B  C  D  E  COUNT
     001  0  0  1  1  0  2
     002  1  1  1  1  1  5
     003  0  1  0  1  0  2
     004  1  1  1  0  0  3

DADOS_FILTRADOS = DADOS %>%
filter(COUNT > 3)

print(DADOS_FILTRADOS)

    CODE  A  B  C  D  E  COUNT
     002  1  1  1  1  1  5

What I would like to do is find the difference between these two data.frames, ie make the table DADOS except the table DADOS_FILTRADOS. What could be done?

  • 1

    See if this reply can help.

  • 1

    @user108927 I will check.

1 answer

2


Within the , the package presents the solution of anti_join().

First, let’s reproduce the data,

txt1 <- "CODE  A  B  C  D  E  COUNT
001  0  0  1  1  0  2
002  1  1  1  1  1  5
003  0  1  0  1  0  2
004  1  1  1  0  0  3"

txt2 <- "CODE  A  B  C  D  E  COUNT
002  1  1  1  1  1  5"

dados <- read.table(text = txt1, header = TRUE)
dados_filtrados <- read.table(text = txt2, header = TRUE)

Now we can check the difference. The function anti_join() has three main arguments

  1. x: the table that will be returned without the matching records
  2. y: the table in which it will be used to delete the records of the first
  3. by: the name of the fields that should be used as key

The code then goes like this:

library(dplyr)

anti_join(dados, dados_filtrados, "CODE")
#   CODE A B C D E COUNT
# 1    1 0 0 1 1 0     2
# 2    3 0 1 0 1 0     2
# 3    4 1 1 1 0 0     3

That repository has several gifs to help understand some ideas have manipulation/union of tables. In particular the anti_join() is here.

  • Tomás will test, it seems to be very simple. I imagined that "operations" between data.frames were more complex.

  • 1

    Take a look at the link that included, it helps to see the simplicity of these operations.

  • I will look yes @Tomás Barcellos =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.