→ lilian0330: 感謝!我研究一下! 04/04 21:16
推 lilian0330: 我跑完了可以執行,但換成原始資料後遇到一個問題 04/04 21:46
→ lilian0330: geodist[pair[1], pair[2]] : no 'dimnames' attribut 04/04 21:46
→ lilian0330: for array 04/04 21:46
→ andrew43: 你比較我的資料matrix和你的看是不是少了欄名或列名 04/04 22:00
→ andrew43: 真的解不開就直接提供你的部份資料。 04/04 22:01
→ andrew43: 若你可以看懂code,相信這只是個小問題,修一下即可。 04/04 22:03
推 lilian0330: 我找到了,距離矩陣沒有原本的樣本名字 04/04 22:06
→ lilian0330: 但是因為我要用經緯度算,所以使用gdistance package 04/04 22:07
→ lilian0330: 中的spDists(),只有在輸出成csv的時候是有site的 04/04 22:08
→ andrew43: 那好辦,就多幫它補上即可。 04/04 22:21
推 lilian0330: 謝謝你!我補上了 04/04 22:24
→ lilian0330: 現在新的 Error in combn(., 2) : n < m 04/04 22:24
推 lilian0330: m是2,n是什麼呀? 04/04 22:26
→ andrew43: 你檢查是不是有某個site只有一個物種。應該是這個原因 04/04 22:28
→ andrew43: 有的話,這段code要修以跳脫這種例外。 04/04 22:29
→ andrew43: 說反了,是不是某個物種只出現在一個site。 04/04 22:30
推 lilian0330: 喔喔有的,大概有70%以上~ 04/04 22:32
推 lilian0330: 這種狀況distance定義=0 04/04 22:34
→ andrew43: 把那些物種列都挑掉,或是改寫成if else 04/04 22:34
→ andrew43: 下次把這種明顯的例外一起說明,別人才能一併處理。 04/04 22:35
推 lilian0330: 好的> <抱歉提問的時候沒有想到這是特例...謝謝! 04/04 22:37
推 lilian0330: if x = sum(x) else接原本的code?但我不確定x要改哪裡 04/04 23:01
→ andrew43: 我再回一個 04/04 23:09
location <-
data.frame(
site.name = c("site1", "site2", "site3"),
x = c(3, 1, 16),
row.names = 1
)
dist.mat <-
dist(as.matrix(location)) %>%
as.matrix
dist.mat
spp.dt <-
data.frame(
spp = c("A", "B", "C"),
site1 = c(5, 4, 0),
site2 = c(0, 7, 0),
site3 = c(20, 2, 1)
)
library(magrittr)
spp.dt[, c("site1", "site2", "site3")] %>%
as.matrix %>%
apply(., 1, function(y) {
if (sum(y >= 2)) { # 處理某 spp 只在 1 個以下 site 出現
y[y != 0] %>%
names(.) %>%
combn(., 2) %>%
apply(., 2, function(pair) {
dist.mat[pair[1], pair[2]]
}) %>%
max(.)
} else {
0
}
})
※ 編輯: andrew43 (125.230.106.85), 04/04/2017 23:10:56
※ 編輯: andrew43 (125.230.106.85), 04/04/2017 23:17:33
推 lilian0330: 阿阿不行,出現 Error in dist.mat[pair[1], pair[2]] 04/05 01:17
→ lilian0330: : subscript out of bounds 04/05 01:17
推 lilian0330: 想詢問這邊pair的功能是什麼呢? 04/05 01:19
→ andrew43: 你大概不懂apply怎麼用。把你一小部分資料貼出來吧。 04/05 01:22
→ andrew43: 再看到底是你卡在哪裡。 04/05 01:23
→ andrew43: 你把 dist.mat[pair[1], pair[2]] 改成 print(pair) 就 04/05 01:24
→ andrew43: 可以看到pair實際上是什麼。 04/05 01:24
推 lilian0330: 我看到pair了,但是三筆data有五個結果(site),不太懂 04/05 01:32
→ andrew43: 那就是combn的結果,即所有site的兩兩組合。 04/05 01:32