距離のあるデータフレームがあります
df<-data.frame(site.x=c("A","A","A","B","B","C"),
site.y=c("B","C","D","C","D","D"),Distance=c(67,57,64,60,67,60))
これをクラス「dist」のオブジェクトに変換する必要がありますが、距離を計算する必要がないため、dist() 関数を使用できません。何かアドバイス?
dist オブジェクトを自分で作成することを妨げるものは何もありません。これは、ラベル、サイズなどを設定する属性を持つ単なる距離のベクトルです。
を使用してdf
、これが方法です
dij2 <- with(df, Distance)
nams <- with(df, unique(c(as.character(site.x), as.character(site.y))))
attributes(dij2) <- with(df, list(Size = length(nams),
Labels = nams,
Diag = FALSE,
Upper = FALSE,
method = "user"))
class(dij2) <- "dist"
structure()
または、次の方法で直接行うこともできます。
dij3 <- with(df, structure(Distance,
Size = length(nams),
Labels = nams,
Diag = FALSE,
Upper = FALSE,
method = "user",
class = "dist"))
これらは以下を与えます:
> df
site.x site.y Distance
1 A B 67
2 A C 57
3 A D 64
4 B C 60
5 B D 67
6 C D 60
> dij2
A B C
B 67
C 57 60
D 64 67 60
> dij3
A B C
B 67
C 57 60
D 64 67 60
注:上記は、データが正しい順序であることを確認しません。df
例のように、正しい順序でデータが入っていることを確認してください。つまり、私が示すコードを実行する前に、site.x
次に並べ替えます。site.y
少し前に同様の問題があり、次のように解決しました。
n <- max(table(df$site.x)) + 1 # +1, so we have diagonal of
res <- lapply(with(df, split(Distance, df$site.x)), function(x) c(rep(NA, n - length(x)), x))
res <- do.call("rbind", res)
res <- rbind(res, rep(NA, n))
res <- as.dist(t(res))
?as.dist()
入力として行列が必要ですが、役立つはずです。
Google からやってくる人のために... reshape2 ライブラリの acast 関数は、この種のものにとってはずっと簡単です。
library(reshape2)
acast(df, site.x ~ site.y, value.var='Distance', fun.aggregate = sum, margins=FALSE)