7

それぞれ 2 つの列 (x と y など) を持つ 2 つのデータフレームがあります。2 つのデータフレームを比較して、2 つのデータフレームで x または y または x と y の両方の値が類似しているかどうかを確認する必要があります。

4

2 に答える 2

33

関数を使用all.equalします。データフレームはソートされません。各セルdata frameを別のセルの同じセルと照合するだけです。関数も使えidentical()ます。

于 2012-06-11T12:49:14.020 に答える
8

例がなければ、あなたが何を望んでいるかを理解していると確信できません. しかし、私はあなたがこのようなものが欲しいと思います。もしそうなら、ほぼ確実に同じことを行うためのより良い方法があります。

a <- matrix(c(1,2,
              3,4,
              5,6,
              7,8), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

b <- matrix(c(1,2,
              9,4,
              9,6,
              7,9), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

cc <- matrix(c(NA,NA,
              NA,NA,
              NA,NA,
              NA,NA), nrow=4, byrow=T, dimnames = list(NULL, c("x","y")))

for(i in 1:dim(a)[1]) {
for(j in 1:dim(a)[2]) {
if(a[i,j]==b[i,j]) cc[i,j]=a[i,j]
}
}

cc

編集: 2013 年 1 月 8 日

次の行は、2 つのマトリックス間でどのセルが異なるかを示します。

which(a != b, arr.ind=TRUE)

#      row col
# [1,]   2   1
# [2,]   3   1
# [3,]   4   2

2 つの行列 a と b が同じ場合、次のようになります。

which(a != b)

# integer(0)

which(a != b, arr.ind=TRUE)

# row col

編集 2012 年 1 月 9 日

次のコードは、行名が に与える影響と、2 つのデータ フレームのいずれかが 3 番目のデータ フレームをサブセット化することによって作成される場合を示していidenticalます。比較される 2 つのデータ フレーム間で行名が異なる場合、どちらも も も返しません。ただし、列を比較したり、2 つのデータ フレームを比較したりするために使用できます。比較される 2 つのデータ フレームのそれぞれに対して行名が に設定されている場合、両方ともとが返されます。all.equalwhichidenticalall.equalTRUEwhichxyNULLidenticalall.equalTRUE

df1 <- read.table(text = "
     group  x  y 
       1   10 20
       1   10 20
       1   10 20
       1   10 20
       2    1  2
       2    3  4
       2    5  6
       2    7  8
", sep = "", header = TRUE)

df2 <- read.table(text = "
     group  x  y 
       2    1  2
       2    3  4
       2    5  6
       2    7  8
", sep = "", header = TRUE)

# df3 is a subset of df1

df3 <- df1[df1$group==2,]

# rownames differ between df2 and df3 and
# therefore neither 'all.equal' nor 'identical' return TRUE
# even though the i,j cells of df2 and df3 are the same.
# Note that 'which' indicates no i,j cells differ between df2 and df3 

df2
df3

all.equal(df2, df3)
identical(df2, df3)
which(df2 != df3)

# set row names to NULL in both data sets and
# now both 'all.equal' and 'identical' return TRUE.
# Note that 'which' still indicates no i,j cells differ between df2 and df3

rownames(df2) <- NULL
rownames(df3) <- NULL

df2
df3

all.equal(df2, df3)
identical(df2, df3)
which(df2 != df3)
于 2012-06-11T12:07:10.113 に答える