Reputation: 21
Created a matrix named GroMatrix.
GroMatrix=matrix(c(1,2,3,4,5,2,3,4,5,6,3,4,5,6,7,4,5,6,7,8),byrow=TRUE,nrow=4)
I want to use this matrix as reference for entering data in a new column of my existing data frame by looking up data from two different columns of the same row to be treated as row number and column number of matrix. I was trying with following method but in vain.
Df$NewCol=GroMatrix[Df$Col1,Df$Col2]
Col1 and Col2 are two variables of Dataframe Df and both these columns are numeric (integers). On running the above command, I am getting a number of new observations added to my dataframe namely NewCol[,1], NewCol[,2], and so on. Need help .
Upvotes: 2
Views: 49
Reputation: 26238
You just need to subset matrix through a matrix.
So, to subset matrix through matrix you have to convert your dataset into a matrix. Use as.matrix
for that. Moreover, subsetting matrix through a matrix gives us a vector. For more reading, please see Advanced R by Hadley Wickham
Let's suppose your reference cols in data frame are named row
and col
. Just follow these steps
Gromatrix <- matrix(c(1,2,3,4,5,2,3,4,5,6,3,4,5,6,7,4,5,6,7,8),byrow=TRUE,nrow=4)
set.seed(1)
df_samp <- data.frame(
row = sample(1:4, 10, replace = TRUE),
col = sample(1:5, 10, replace = TRUE)
)
df_samp$new_col <- Gromatrix[as.matrix(df_samp[, c('row', 'col')])]
df_samp
#> row col new_col
#> 1 1 3 3
#> 2 4 3 6
#> 3 3 1 3
#> 4 1 5 5
#> 5 2 5 6
#> 6 1 2 2
#> 7 3 2 4
#> 8 3 1 3
#> 9 2 5 6
#> 10 2 5 6
Created on 2022-07-07 by the reprex package (v2.0.1)
Upvotes: 2