user8853874
user8853874

Reputation:

how add the entry ij-th of a matrix to a data Fram who has column i and row j

I have a data frame. with two column A and B. I want add one more column C to this from a matrix where the Column A is i and column B is j. for example suppose I have

          A        B
          1        3
          2        2

and I have a matrix

M:

    1     3     0 
    2     4      5
    2     1     6

the new column C is first row and tired column and second row and second column:

          A        B       C
          1        3       0
          2        2       4

Upvotes: 1

Views: 26

Answers (1)

akrun
akrun

Reputation: 887501

We can convert the data.frame to matrix and use that as row/column index to extract the values from 'M' and assign it to new column in 'df1'

df1['C'] <-  M[as.matrix(df1)]
df1
#  A B C
#1 1 3 0
#2 2 2 4

Or another option is to cbind (which by default creates a matrix) the extracted columns from data.frame

df1['C'] <- M[cbind(df1$A, df1$B)]

data

df1 <- data.frame(A = 1:2, B = c(3, 2))
M <- cbind(c(1, 2, 2), c(3, 4, 1), c(0, 5, 6))

Upvotes: 1

Related Questions