I have an empty matrix m:
m <- matrix(0, nrow = 4, ncol = 2, byrow = TRUE,
dimnames = list(c("sp1", "sp2", "sp3", "sp4"),
c("x", "y")))
And need to fill the matrix using the data frame 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))
so that if rowname(m) is equal to d[, "species"] and m[, "x"] is equal to the d[, "site"] then d[, "freq"] in entered in the correct place in matrix m i.e. returning:
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")))
I have tried:
m[d[, c("species", "x")]] <- d[, "freq"]
I suspect I am not doing the data frame indexing properly? Any ideas? Thanks.
That is probably not the best way to do it but this is working: