如何使用原始数据帧中的列名和行名将矩阵转换为数据帧

时间:2019-04-16 06:19:06

标签: r dataframe matrix

我有以下原始数据框:

original_df <- structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0), .Dim = c(3L, 3L), .Dimnames = list(
  c("foo", "bar", "qux"), c("A", "B", "C")
))

original_df
#>     A B C
#> foo 0 0 0
#> bar 0 1 0
#> qux 0 0 0

然后我进行一些转换,形成一个纯矩阵:

transformed_mat <- structure(c(
  -2.96100772320745e-06, 1.68169240440672e-05, -0.000126831814542474,
  -9.94017331567414e-07, 0.000763027661834236, -0.000103315552273569,
  -2.22776698138103e-06, 2.94317362067914e-05, -0.000190660599719715
), .Dim = c(3L, 3L))

transformed_mat
#>               [,1]          [,2]          [,3]
#> [1,] -2.961008e-06 -9.940173e-07 -2.227767e-06
#> [2,]  1.681692e-05  7.630277e-04  2.943174e-05
#> [3,] -1.268318e-04 -1.033156e-04 -1.906606e-04

如何用original data frame中的列名和行名来掩盖转换后的矩阵?

所需的结果是:

                A            B              C
foo -2.961008e-06 -9.940173e-07 -2.227767e-06
bar  1.681692e-05  7.630277e-04  2.943174e-05
qux -1.268318e-04 -1.033156e-04 -1.906606e-04

2 个答案:

答案 0 :(得分:1)

我们可以使用dimnames分配,因为它们都是matrix es

dimnames(transformed_mat) <- dimnames(original_df)
transformed_mat
#                A             B             C
#foo -2.961008e-06 -9.940173e-07 -2.227767e-06
#bar  1.681692e-05  7.630277e-04  2.943174e-05
#qux -1.268318e-04 -1.033156e-04 -1.906606e-04

由于dimnames是一个属性,另一种方式是通过赋值attr

attr(transformed_mat, "dimnames") <- attr(original_df, "dimnames")

答案 1 :(得分:1)

简单使用:dimnames(transformed_mat)<-dimnames(original_df)

请参见下面的工作示例:

> transformed_mat
            A             B             C
foo -2.961008e-06 -9.940173e-07 -2.227767e-06
bar  1.681692e-05  7.630277e-04  2.943174e-05
qux -1.268318e-04 -1.033156e-04 -1.906606e-04
>
>
>
> original_df <- structure(c(0, 0, 0, 0, 1, 0, 0, 0, 0), .Dim = c(3L, 3L), .Dimnames = list(
+     c("foo", "bar", "qux"), c("A", "B", "C")
+ ))
> original_df
A B C
foo 0 0 0
bar 0 1 0
qux 0 0 0
> transformed_mat <- structure(c(
+     -2.96100772320745e-06, 1.68169240440672e-05, -0.000126831814542474,
+     -9.94017331567414e-07, 0.000763027661834236, -0.000103315552273569,
+     -2.22776698138103e-06, 2.94317362067914e-05, -0.000190660599719715
+ ), .Dim = c(3L, 3L))
> transformed_mat
              [,1]          [,2]          [,3]
[1,] -2.961008e-06 -9.940173e-07 -2.227767e-06
[2,]  1.681692e-05  7.630277e-04  2.943174e-05
[3,] -1.268318e-04 -1.033156e-04 -1.906606e-04
> dimnames(transformed_mat)<-dimnames(original_df)
> transformed_mat
                A             B             C
foo -2.961008e-06 -9.940173e-07 -2.227767e-06
bar  1.681692e-05  7.630277e-04  2.943174e-05
qux -1.268318e-04 -1.033156e-04 -1.906606e-04