2012-06-20 101 views
1

我有一個空的矩陣m一個矩陣:灌裝使用數據幀中的R

m <- matrix(0, nrow = 4, ncol = 2, byrow = TRUE, 
      dimnames = list(c("sp1", "sp2", "sp3", "sp4"), 
          c("x", "y"))) 

而且需要使用數據幀d來填充矩陣

d <- data.frame(site = c("x", "y", "u", "v"), 
       species = c("sp1", "sp1", "sp1", "sp1"), 
       freq = c(0.2, 0.3, 0.5, 0.1)) 

使得如果rowname(m)等於d[, "species"]m[, "x"]等於d[, "site"]然後d[, "freq"]輸入正確的地方在矩陣m即返回:

m <- matrix(c(0.2, 0, 0, 0, 0, 0, 0, 0), nrow = 4, ncol = 2, byrow = TRUE, 
      dimnames = list(c("sp1", "sp2", "sp3", "sp4"), 
          c("x", "y"))) 

我曾嘗試:

m[d[, c("species", "x")]] <- d[, "freq"] 

我懷疑我是不是在做數據幀索引是否正確?有任何想法嗎?謝謝。

回答

2

這可能不是做的最好辦法但這是工作:

for(i in 1:nrow(d)){m[rownames(m)==d[i,2],colnames(m)==d[i,1]] <- d[i,3]} 
+0

謝謝!這工作。你會預見到它的任何穩定性問題嗎? – Elizabeth

+0

我真的想不出任何。 – plannapus

1

鑄造和合並的組合工作正常。

設置數據

m <- matrix(0, nrow = 4, ncol = 2, byrow = TRUE, 
      dimnames = list(c("sp1", "sp2", "sp3", "sp4"), 
          c("x", "y"))) 
d <- data.frame(site = c("x", "y", "u", "v"), 
       species = c("sp1", "sp1", "sp1", "sp1"), 
       freq = c(0.2, 0.3, 0.5, 0.1)) 

做一些計算

library(reshape) 
dc <- cast(species ~ site, data = d, value = "freq") 
md <- as.data.frame(m) 
md$species <- rownames(md) 
md <- merge(
    md, 
    dc[, c("species", "x")], 
    all.x = TRUE, 
    by = "species", 
    suffixes = c("", ".tmp")) 
md$x[!is.na(md$x.tmp)] <- md$x.tmp[!is.na(md$x.tmp)] 
md$x.tmp <- NULL 

,當您轉換d $的網站包含rownames(M)

d <- data.frame(
    site = c("x", "y", "u", "v"), 
    species = factor(
     c("sp1", "sp1", "sp1", "sp1"), 
     levels = c("sp1", "sp2", "sp3", "sp4")), 
    freq = c(0.2, 0.3, 0.5, 0.1)) 
cast(species ~ site, data = d, value = "freq", add.missing = TRUE) 
的因素你可以symplify代碼

你可以獲得y,u和v的頻率作爲獎勵。如果你不想讓他們,從DA先驗

cast(species ~ site, data = d, value = "freq", add.missing = TRUE, 
    subset = site == "x") 

刪除它們使用填充參數是要NA轉換到另一個值

cast(species ~ site, data = d, value = "freq", add.missing = TRUE, 
    subset = site == "x", fill = 0) 
+0

謝謝!我最終使用plannapus的答案,因爲它更短。你的版本是否更穩定? – Elizabeth

+0

我已添加到代碼簡化代碼。這一切都取決於m是否已經定義或者是否可以從d創建m。 – Thierry