2017-07-17 7 views
1

私は2つのベクトルを持ち、ベクトルのどのインデックスが同一でないかを知りたい。 NA == NANAを、NA == 5NAを生成しているため、これを行う方法がわかりません。誰かがガイダンスを提供できますか?R:2つのベクトルの同一でない要素を特定する

# Create data with NA vs. 3 
dat1 <- data.frame(foo = c(NA, 5, 9), 
        bar = c(3, 5, 9)) 

# Create data with NA vs. NA 
dat2 <- data.frame(foo = c(NA, 5, 9), 
        bar = c(NA, 5, 9)) 

# Produces same result 
dat1$foo == dat1$bar 
dat2$foo == dat2$bar 

identical((dat1$foo == dat1$bar), (dat2$foo == dat2$bar)) 
+1

'ind = dat1 $ foo!= dat1 $ bar; which(is.na(ind)| ind) ' –

+0

シンプルで華麗です。答えとして追加してください。 – user3614648

答えて

3

編集

私たちは列の両方でNA年代を持っている場合は、以下の解決策は機能しません。それを処理するために、我々は関数を宣言することができます

dissimilar_index <- function(dat) { 
    ind = with(dat, (foo == bar) | (is.na(foo) & is.na(bar))) 
    which(is.na(ind) | !ind) 
} 

dissimilar_index(dat1) 
#[1] 1 

dissimilar_index(dat2) 
#integer(0) 

、ここで

ind = !with(dat1, is.na(foo) == is.na(bar) & foo == bar) 
which(!is.na(ind) & ind) 
#[1] 1 

ind = !with(dat2, is.na(foo) == is.na(bar) & foo == bar) 
which(!is.na(ind) & ind) 
#integer(0) 

を新しいデータフレーム我々はまた、使用することができますdat3

dat3 = rbind(dat1, c(2, 3)) 
dat3 
# foo bar 
#1 NA 3 
#2 5 5 
#3 9 9 
#4 2 3 

dissimilar_index(dat3) 
#[1] 1 4 

を作成する機能をチェックするために、我々は、かどうかを確認します両方の列がNAであり、両方が等しい。

オリジナル回答

私たちは似ていない列のインデックスを取得し、whichを使用してインデックスを取得するためにNAのための追加のチェックを追加することができます。

ind = dat1$foo != dat1$bar 
which(is.na(ind) | ind) 

#[1] 1 
+0

実際には、NA == NAとNA = 5の区別をするのにはあまり効果がないことに気づいた。NA == NAにTRUEを生成したい/インデックスに含めないことが望ましい。 – user3614648

+0

@ user3614648が答えを更新しました。チェックしてください。 –

+1

私はもっと良いものを考え出すことができませんでした。私の唯一可能な合理化は 'compNA < - function(x、y)union(これは(is.na(x)!= is.na(y))、 foo、dat3 $ bar) ' – thelatemail

0

sapplyidenticalを使用してのアプローチ:

non_ident_ind <- function(df) { 
    which(!sapply(1:nrow(df), function(i) identical(df$foo[i], df$bar[i]))) 
} 

結果:

non_ident_ind(dat1) 
# [1] 1 
non_ident_ind(dat2) 
# integer(0) 

別のアプローチapplyを使用して:

which(apply(dat1, 1, function(r) length(unique(r)) > 1)) 
# [1] 1 
which(apply(dat2, 1, function(r) length(unique(r)) > 1)) 
# integer(0) 
関連する問題