是否有 R 函数可以从列名矩阵中检索值?
Is there an R function to retrieve values from a matrix of column names?
我有一个矩阵 M,它由一行数据框中的列名组成,这样每个列名在数据框中只有一个对应的值。是否有函数可以使用 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
我知道的一种可能方法是将数据框 df
转换为键值对,其中 k = 列名和 v = 值。然后我可以使用以下方法检索值:
apply(M,2,function(x){df[df$k==x,"v"]})
但这对于应该是简单的操作来说似乎过于复杂了...
此外,我不希望使用 dplyr
或 tidyr
之外的任何库,以尽量减少我的代码中所需的依赖关系。
根据 Onyambu 的建议更新为更简单的代码:
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
我有一个矩阵 M,它由一行数据框中的列名组成,这样每个列名在数据框中只有一个对应的值。是否有函数可以使用 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
我知道的一种可能方法是将数据框 df
转换为键值对,其中 k = 列名和 v = 值。然后我可以使用以下方法检索值:
apply(M,2,function(x){df[df$k==x,"v"]})
但这对于应该是简单的操作来说似乎过于复杂了...
此外,我不希望使用 dplyr
或 tidyr
之外的任何库,以尽量减少我的代码中所需的依赖关系。
根据 Onyambu 的建议更新为更简单的代码:
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