Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

r - Match data and count number of same value

I have two data sets (data frames). I would like to find match values between these data sets based on each column names.

intput1 <- structure(list(A = c(1L, 0L, 1L, 0L), B = c(2L, 2L, 1L, 1L), 
C = c(3L, 1L, 1L, 3L)), .Names = c("A", "B", "C"), class = "data.frame", 
row.names = c("1", "2", "3", "4"))

#     A    B   C
#1    1    2   3
#2    0    2   1
#3    1    1   1
#4    0    1   3

input2 <- structure(list(A = c(1L, 3L, 1L, 0L), B = c(1L, 2L, 0L, 1L), 
C = c(2L, 2L, 1L, 2L)), .Names = c("A", "B", "C"), class = "data.frame", 
row.names = c("1", "2", "3", "4"))

#     A    B   C
#1    1    1   2
#2    3    2   2
#3    1    0   1
#4    0    1   2

Expected output:

#     colnames.1   colnames.2   match
#1             A           A        3
#2             A           B        1
#3             A           C        1
#4             B           A        1
#5             B           B        2
#6             B           C        2
#7             C           A        1
#8             C           B        0
#9             C           C        1

where the final column is the number of matches.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is a possibility:

f <- function (x, y) sum(x == y)

oo <- outer(input1, input2, Vectorize(f))

#  A B C
#A 3 1 1
#B 1 2 3
#C 1 0 1

as.data.frame.table(oo)

#  Var1 Var2 Freq
#1    A    A    3
#2    B    A    1
#3    C    A    1
#4    A    B    1
#5    B    B    2
#6    C    B    0
#7    A    C    1
#8    B    C    3
#9    C    C    1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...