在R中使用数据框填充矩阵 [英] Filling a matrix using a dataframe in R
本文介绍了在R中使用数据框填充矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个空矩阵 m
:
m <- matrix(0, nrow = 4, ncol = 2, byrow = TRUE,
dimnames = list(c("sp1", "sp2", "sp3", "sp4"),
c("x", "y")))
还需要使用数据框填充矩阵d
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))
所以如果 rowname(m)
等于 d [,species]
和 m [,x]
等于 d [ site]
then d [,freq]
输入到矩阵中的正确位置,即返回:
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")))
我尝试过:
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:
for(i in 1:nrow(d)){m[rownames(m)==d[i,2],colnames(m)==d[i,1]] <- d[i,3]}
这篇关于在R中使用数据框填充矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文