Checking for identical columns in a data frame in R

后端 未结 3 1706
南方客
南方客 2020-12-30 23:47

Suppose you have a data frame called data with two identical columns:

A B
1 1
2 2
3 3
4 4

How can I check if these two columns are identica

相关标签:
3条回答
  • 2020-12-31 00:30

    You could use identical

    identical(DT[['A']],DT[['B']])
    
    0 讨论(0)
  • 2020-12-31 00:32

    This might be overkill for your problem, but you may also want to look into compare() from the "compare" package. Consider the following examples:

    > data <- data.frame(A = c(1, 2, 3, 4), B = c(1, 2, 3, 4))
    > compare(data[1], data[2]) ## Should be false
    FALSE [TRUE]
    > compare(data[1], data[2], ignoreNames = TRUE) # Allow different names
    TRUE
      dropped names
    > data <- data.frame(A = c(1, 2, 3, 4), B = as.character(c(1, 2, 3, 4)))
    > str(data) ## "B" is now a factor, so use `coerce` to test for equality
    'data.frame':   4 obs. of  2 variables:
     $ A: num  1 2 3 4
     $ B: Factor w/ 4 levels "1","2","3","4": 1 2 3 4
    > compare(data[1], data[2], ignoreNames = TRUE, coerce = TRUE)
    TRUE
      [A] coerced from <factor> to <numeric>
      dropped names
    

    There is a general logical argument, allowAll, that can be set to TRUE to allow the compare function to try different transformations to test for equality.

    0 讨论(0)
  • 2020-12-31 00:39

    You could use all():

    > data <- data.frame(A=c(1,2,3,4), B=c(1,2,3,4))
    > all(data$A == data$B)
    [1] TRUE
    
    0 讨论(0)
提交回复
热议问题