从矩阵动态获取值

时间:2019-05-22 15:33:51

标签: r matrix

我想基于转换矩阵中的值将新列添加到数据框。

我尝试了此解决方案[R extract values from matrix given dataframe of x and y,但它似乎适用于数字作为索引,并且行和列都有字符名称。

例如:

r
x<- 
cbind(c(0.3,0.35,0.35,0),c(0.2,0.2,0.4,0.2)
,c(0,0.6,0.1,0.3),c(0.5,0.25,0.25,0))
colnames(x) <- c("A","B","C","D")
rownames(x) <- c("A","B","C","D")

y<-as.data.frame(cbind(c(1,2,3,4,5,6)
,c("A","A","B","A","B","A"),c("D","C","C","D","D","D")))
colnames(y) <- c("id","e1","e2")

index_df = y%>% select(e1,e2)
colnames(index_df)<-c('rows','cols')

y[as.matrix(index_df)]

我收到此错误

  

as.matrix(x)[i]中的错误:下标超出范围

我想用矩阵中的值在y数据框中添加列名l1

   id e1 e2 l1  
1  1  A  D  0.50  
2  2  A  C  0.0  
3  3  B  C  0.2  
4  4  A  D  0.50  
5  5  B  D  0.25  
6  6  A  D  0.50  

1 个答案:

答案 0 :(得分:1)

我们需要使用正确的数据集来提取值。在这里,“ y”没有匹配的行或列。是“ x”

y$l1 <- x[as.matrix(index_df)]
y$l1
#[1] 0.50 0.00 0.60 0.50 0.25 0.50