Compare objects in R

Asked

Viewed 298 times

5

I have two dataframes:

atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa
1995-01-01        74.35501        35.59109
1995-02-01        74.06131        35.43400
1995-03-01        74.06131        35.93259

and:

atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa PIMPF_Br_A_3_sa
1995-01-01        74.35501        35.59109        79.39399
1995-02-01        74.06131        35.43400        79.29079
1995-03-01        74.06131        35.93259        79.22728

I’m using the function identical to check if the two are equal and would like to return FALSE, return the column that is different between the two dataframes.

The code I’m using:

comparar <- identical(df1, df2)
if (comparar == TRUE){
    print("Os dados são iguais")
} else {
    print("Os dados não são iguais")
}

1 answer

6


This function compares column by column with identical and has as output a logical vector with the names of the columns of the first dataframe. If a column name exists in the first df but not in the second, the value is NA.

comparar <- function(DF1, DF2){
  inx <- match(names(DF1), names(DF2))
  res <- sapply(inx, function(i) {
    if(is.na(i))
      NA
    else
      identical(DF1[i], DF2[i])
  })
  names(res) <- names(DF1)
  res
}

comparar(df1, df2)
#     atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa 
#           TRUE            TRUE            TRUE 
comparar(df2, df1)
#     atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa PIMPF_Br_A_3_sa 
#           TRUE            TRUE            TRUE              NA 

Dice.

df1 <- read.table(text = "
atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa
1995-01-01        74.35501        35.59109
1995-02-01        74.06131        35.43400
1995-03-01        74.06131        35.93259
", header = TRUE)


df2 <- read.table(text = "
atualizada PIMPF_Br_A_1_sa PIMPF_Br_A_2_sa PIMPF_Br_A_3_sa
1995-01-01        74.35501        35.59109        79.39399
1995-02-01        74.06131        35.43400        79.29079
1995-03-01        74.06131        35.93259        79.22728
", header = TRUE)

Browser other questions tagged

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