使用R中的数据框填充矩阵

时间:2012-06-20 08:57:24

标签: r matrix indexing dataframe

我有一个空矩阵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"]

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

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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 $ 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")

使用fill参数是否要将NA转换为其他值

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