Oscar Benitez
Oscar Benitez

Reputation: 267

Dynamically get the values from a matrix

I want to add a new column to my data frame based on values from a transition matrix.

I tried this solution [R extract values from matrix given dataframe of x and y but it seems to work for numbers as indexes, and I have character names for my rows and columns.

For example:

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

I get this error

Error in as.matrix(x)[i] : subscript out of bounds

I want to add a column names l1 to y data frame with the values from the matrix

   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  

Upvotes: 1

Views: 191

Answers (1)

akrun
akrun

Reputation: 887831

We need to use the right dataset to extract the values. Here, 'y' doesn't have the rows or columns matching. It is 'x'

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

Upvotes: 1

Related Questions