Isaac Fink
Isaac Fink

Reputation: 85

Is there an R function to retrieve values from a matrix of column names?

I have a matrix M consisting of column names from a data frame with one row, such that each column name has just one corresponding value in the data frame. Is there a function to create a new matrix with the corresponding values from the column names in M?

M <- t(data.frame(A=c("label_1","label_2","label_3"),
                  B=c("label_4","label_5","label_6"),
                  C=c("label_7","label_8","label_9")))
M
>   [,1]      [,2]      [,3]     
A "label_1" "label_2" "label_3"
B "label_4" "label_5" "label_6"
C "label_7" "label_8" "label_9"

df <- data.frame(label_2=5, label_1=0, label_4=7,
                 label_6=15, label_3=12, label_5=11,
                 label_9=9, label_8=15, label_7=35)
df
>   label_2 label_1 label_4 label_6 label_3 label_5 label_9 label_8 label_7
1       5       0       7      15      12      11       9      15      35

## I want to create a new data.frame with the values from these labels
> [,1] [,2] [,3]
A    0    5   12
B    7   11   15
C   35   15    9

One possible way I'm aware of is to convert the data frame df to a key-value pair, with k = column names and v = values. I could then retrieve the values using:

apply(M,2,function(x){df[df$k==x,"v"]})

But this seems too overcomplicated for what should be a simple operation...

Additionally, I would prefer not to use any libraries outside of dplyr or tidyr to minimize the dependencies needed in my code.

Upvotes: 0

Views: 76

Answers (1)

Roee Anuar
Roee Anuar

Reputation: 3436

Updated to an easier code using Onyambu's suggestion:

M <- t(data.frame(A=c("label_1","label_2","label_3"),
                  B=c("label_4","label_5","label_6"),
                  C=c("label_7","label_8","label_9")))

df <- data.frame(label_2=5, label_1=0, label_4=7,
                 label_6=15, label_3=12, label_5=11,
                 label_9=9, label_8=15, label_7=35)

P<-matrix(df[c(M)],nrow(M))
P
> P
     [,1] [,2] [,3]
[1,] 0    5    12  
[2,] 7    11   15  
[3,] 35   15   9   

Upvotes: 1

Related Questions