假設你想找到的每一列,你可以使用類似這樣每隔一列之間的夾角的餘弦值:
sapply(df, function(y) sapply(df,get.cos,y))
下面是完整的代碼。
df = read.table(h=T,row.names=1,text="
A B C D E F
A 0 0 1 0 1 0
B 1 0 0 0 1 0
C 1 0 0 1 0 0
D 0 0 0 0 0 1
E 1 1 0 1 0 1
F 0 0 1 0 1 0")
get.cos <- function(x,y) sum(x*y)/sqrt(sum(x*x)*sum(y*y))
# using loops
result.1 <- matrix(NA, nc=ncol(df),nr=nrow(df))
for(i in 1:ncol(df)) {
for(j in 1:ncol(df)) {
result.1[i,j] <- get.cos(df[,i],df[,j])
}
}
result.1
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1.0000000 0.5773503 0.0000000 0.8164966 0.3333333 0.4082483
# [2,] 0.5773503 1.0000000 0.0000000 0.7071068 0.0000000 0.7071068
# [3,] 0.0000000 0.0000000 1.0000000 0.0000000 0.8164966 0.0000000
# [4,] 0.8164966 0.7071068 0.0000000 1.0000000 0.0000000 0.5000000
# [5,] 0.3333333 0.0000000 0.8164966 0.0000000 1.0000000 0.0000000
# [6,] 0.4082483 0.7071068 0.0000000 0.5000000 0.0000000 1.0000000
# using sapply(...)
result.2 <- sapply(df, function(y) sapply(df,get.cos,y))
result.2
# A B C D E F
# A 1.0000000 0.5773503 0.0000000 0.8164966 0.3333333 0.4082483
# B 0.5773503 1.0000000 0.0000000 0.7071068 0.0000000 0.7071068
# C 0.0000000 0.0000000 1.0000000 0.0000000 0.8164966 0.0000000
# D 0.8164966 0.7071068 0.0000000 1.0000000 0.0000000 0.5000000
# E 0.3333333 0.0000000 0.8164966 0.0000000 1.0000000 0.0000000
# F 0.4082483 0.7071068 0.0000000 0.5000000 0.0000000 1.0000000
嘗試使用'apply' – arodrisa
請提供一個可重複使用的'set'示例和您想要應用的函數。你的代碼是無效的語法, – Roland
你打算第一行是'for(i in 1:nrow(matrix))'嗎? – Whitebeard