【发布时间】:2014-07-17 19:50:14
【问题描述】:
我需要比较两个数据帧并生成比较结果的输出。尺寸相同。列和行顺序匹配。我想比较两个数据帧之间的每个对应单元格,并确定它们是否包含相同的值或不同的值。如果值不同,我需要知道这两个值是否属于我定义的特定向量,或者它们是否来自 2 个不同的向量。我在下面提供了示例代码。
我无法在论坛中找到完全符合我需要的任何内容,主要是因为我需要知道值何时不同,根据我提供的标准它们有何不同。
#Possible Value Types for the Data Frames
typeA = c("Green", "Blue", "Purple")
typeB = c("Red", "Orange", "Yellow")
#Create Data Frames to Compare
df1 = as.data.frame(cbind(rbind("Green","Red","Yellow"),
rbind("Green", "Purple", "Red"),
rbind("Orange", "Orange",NA),
rbind(NA,"Red","Purple")))
df2 = as.data.frame(cbind(rbind("Green","Red","Yellow"),
rbind(NA, "Purple", "Yellow"),
rbind("Blue", "Orange",NA),
rbind("Blue","Red","Green")))
#Data frames compared must have identical dimensions
###INSERT FUNCTION HERE
myfunction = function(df1,df2){
#compare corresponding cells and provide output based on match
#example: compare cell df1[1,1] to df2[1,1]
#if either df1[1,1] or df2[1,1] is NA then return NA, else...
#if df1[1,1] matches df2[1,1] then return "Match"
#if df1[1,1] does not match df2[1,1] but they are both in vector typeB then return "SAMEGROUP"
#if df1[1,1] does not match df2[1,1] and one is in vector typeA and the other in typeB then return "DIFFGROUP"
}
###RUN FUNCTION
df.out = myfunction(df1,df2)
#expected output
#Match: The values in df1 and df2 for that cell are identical
#SAMEGROUP: The values in df1 and df2 for that cell are different, but
##they come from the same group (typeA or typeB)
#DIFFGROUP: The values in df1 and df2 for that cell are different, and
##they come from different groups (one from typeA, one from typeB)
#NA: One or both of the corresponding cells in df1 or df2 has an NA
df.out = as.data.frame(cbind(rbind("Match","Match","Match"),
rbind(NA, "Match", "SAMEGROUP"),
rbind("DIFFGROUP", "Match",NA),
rbind(NA,"Match","SAMEGROUP")))
谢谢!
【问题讨论】:
-
它们有什么不同是什么意思?您似乎没有向我们提供有关您提供的差异标准的任何信息。我可以给你一段代码来确定给定的表格位置是否在相应的表格中匹配,但这只是你的问题。这对我来说似乎是两个问题。
-
我的数据框中的值可以分组。在我的示例中,typeA 和 typeB。你可以把它想象成一组偶数和一组奇数。然后提出问题,数字是否相同?如果不是,它们是偶数还是奇数,还是一个偶数一个奇数?