2013-12-12 50 views

回答

3

這裏有一個辦法:

# find the values present in both row names and column names 
is <- do.call(intersect, unname(dimnames(x))) 

# calculate the sum 
sum(x[cbind(is, is)]) 

其中x是你的表。

+1

我喜歡使用intersect'和傳球的''要到cbind'做一個字符索引,但不能看到'unname'的需要。 –

+0

@DWin用'x < - table(data.frame(a = rep(1:3,4),b = sample(0:2,12,TRUE)))'而不用'unname'嘗試它。 –

1

再一個,不言自明:

sum(x[colnames(x)[col(x)] == rownames(x)[row(x)]]) 
+0

我覺得這是最優雅的一個 – vonjd

相關問題