Find equal columns in data.frames

I have two data.frame objects 'x' and 'ans1', 500 columns in 'x' and 7 columns in 'ans1' How can I find column names from "x" that are equal to columns from "ans1"?

+2
source share
3 answers

C %in%:

names(x) %in% names(ans1)

See more details ?match.

+1
source

Could use identical()with package digest:

library(digest)

x <- data.frame(aa = c("s", "d", "f"), bb = 1:3)
ans1 <- data.frame(bb = c("d", "s", "z"), cc = 1:3)

(myMatches<-lapply(x, function(myX) sapply(ans1,
  function(y) identical(digest(y), digest(myX))))
)

# $aa
#    bb    cc 
# FALSE FALSE 

# $bb
#    bb    cc 
# FALSE  TRUE

This means that the data in the column bbin data.frame is xequal to the data in the column ccin data.frame ans1.

To get only matches,

unlist(lapply(myMatches, function(x) which(x)))
# bb.cc 
# 2

, bb x cc ans1

+2

:

mtcarsSub <- mtcars[c(1,4,7)]
names(mtcarsSub) <- letters[1:3]
matches <- sapply(mtcarsSub,function(x) sapply(mtcars,identical,x))
matches
         a     b     c
mpg   TRUE FALSE FALSE
cyl  FALSE FALSE FALSE
disp FALSE FALSE FALSE
hp   FALSE  TRUE FALSE
drat FALSE FALSE FALSE
wt   FALSE FALSE FALSE
qsec FALSE FALSE  TRUE
vs   FALSE FALSE FALSE
am   FALSE FALSE FALSE
gear FALSE FALSE FALSE
carb FALSE FALSE FALSE

names(mtcars)[apply(matches,2,which)]
[1] "mpg"  "hp"   "qsec"
+1
source

Source: https://habr.com/ru/post/1658229/


All Articles