2014-05-22 86 views
0

所以我試圖做的可能是非常基本的,所以請原諒我的無知。在R中比較數字和接收二進制輸出

我的倍數變化兩列由一個矩陣:

mat<-matrix(rexp(10, rate=.1), ncol=2) 
colnames(mat)<-c("ctr","tst") 
mat 
      ctr  tst 
[1,] 3.80024188 3.450514 
[2,] 3.19933014 5.315761 
[3,] 0.01122948 4.398819 
[4,] 21.86070191 26.109626 
[5,] 5.38260987 1.678203 

我想要做的是添加包含一個二進制「1」或「0」值作爲輸出的第三列比較ctr列中的倍數變化與tst列,以及一些提供的容差,例如0.75。

因此,基本上,mat [1,3]的新列中的值,其將mat [1,1]和mat [1,2]比較,將是「0」(相差小於0.75) [3,3]比較mat [3,1]和mat [3,2]將包含值「1」(相差0.75以上)。我需要將「Inf」和「-Inf」值與常規數字進行比較,因爲我的一些摺疊變化出現在「Inf」或。! 「-Inf」 提前

感謝

+0

你應該指定當'Inf'和'-Inf'與實際值進行比較時你會發生什麼。總是1? – joran

回答

1

定義返回TRUE每當兩個輸入或者是不超過0.75分開,或兩者Inf,或兩者-Inf一個比較函數:

compare <- function(xx) { 
    if ((xx[1]==Inf & xx[2]==Inf) | (xx[1]==-Inf & xx[2]==-Inf)) { 
     TRUE 
    } else { 
     abs(diff(xx))<=0.75 
    } 
} 

Th烯創建測試矩陣和apply此函數(以使用!用於TRUE非標準映射其邏輯逆0且FALSE到1):

> set.seed(1) 
> mat <- rbind(matrix(rexp(10, rate=.1), ncol=2),c(1,Inf),c(-Inf,0),c(Inf,Inf),c(Inf,-Inf),c(-Inf,-Inf)) 
> colnames(mat)<-c("ctr","tst") 
> 
> cbind(mat,!apply(mat,1,compare)) 
      ctr  tst 
[1,] 7.551818 28.949685 1 
[2,] 11.816428 12.295621 0 
[3,] 1.457067 5.396828 1 
[4,] 1.397953 9.565675 1 
[5,] 4.360686 1.470460 1 
[6,] 1.000000  Inf 1 
[7,]  -Inf 0.000000 1 
[8,]  Inf  Inf 0 
[9,]  Inf  -Inf 1 
[10,]  -Inf  -Inf 0 
> 
+0

完美!正是我想要的。非常感謝Stephan。 –

2

僅有瞎猜:

set.seed(123) 
mat<-matrix(rexp(10, rate=.1), ncol=2) 
colnames(mat)<-c("ctr","tst") 
#Add some Inf examples 
mat[4,1] <- Inf 
mat[2,2] <- -Inf 
mat <- cbind(mat,(abs(mat[,1] - mat[,2]) >= 0.75) + 0L) 
mat 

##   ctr  tst 
##[1,] 8.4345726 3.1650122 1 
##[2,] 5.7661027  -Inf 1 
##[3,] 13.2905487 1.4526680 1 
##[4,]  Inf 27.2623646 1 
##[5,] 0.5621098 0.2915345 0