Home > Enterprise >  Fill a matrix in R based on codes
Fill a matrix in R based on codes

Time:06-20

I have a file with codes like this:

V1 V2 
1 1.0000000 
2 0.2000000 
3 0.5000000 
4 0.0000000 

And one matrix with the codes like the following:

1 1 1 1 1 1 1 
3 3 3 3 3 3 3
4 2 4 2 4 2 4
1 1 1 1 1 1 1

I would like to use a loop to make a new matrix in which each value is the value of the codes as follows:

1.0 1.0 1.0 1.0 1.0 1.0 1.0
0.5 0.5 0.5 0.5 0.5 0.5 0.5
0.0 0.2 0.0 0.2 0.0 0.2 0.0
1.0 1.0 1.0 1.0 1.0 1.0 1.0

Any ideas?

CodePudding user response:

Here you can do it somewhat easier because of labels, but in general you can use match:

data:

df_map <- data.frame(
  V1 = c(1, 2, 3, 4),
  V2 = c(1, 0.2, 0.5, 0)
)

m_codes <- matrix(sample(1:4, 32, TRUE), nrow = 4)

solution:

m_values <- matrix(df_map$V2[match(m_codes, df_map$V1)], nrow = nrow(m_codes))
  • Related