1

我有一个空矩阵m

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"]

我怀疑我没有正确地进行数据框索引?有任何想法吗?谢谢。

4

2 回答 2

2

这可能不是最好的方法,但这是有效的:

for(i in 1:nrow(d)){m[rownames(m)==d[i,2],colnames(m)==d[i,1]] <- d[i,3]}
于 2012-06-20T09:39:15.230 回答
1

cast 和 merge 的组合效果很好。

设置数据

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$site 转换为包含 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)

作为奖励,您可以获得 y、u 和 v 的频率。如果您不想要它们,请将它们从先验中删除

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)
于 2012-06-20T09:37:28.020 回答