将矩阵转换为R中的Tibble

b5buobof  于 2023-06-27  发布在  其他
关注(0)|答案(6)|浏览(176)

如何转换这个矩阵:

> matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))
  A
X 1
Y 2
Z 3

在这个Tibble中:

> tibble::tribble(~group1, ~group2, ~value, "X", "A", 1, "Y", "A", 2, "Z", "A", 3)
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <dbl>
1 X      A          1
2 Y      A          2
3 Z      A          3

谢谢你

acruukt9

acruukt91#

如果我们转换为table并强制使用as.data.frame(如果我们需要转换为tibble-使用as_tibble作为as.data.frame的 Package 器),则使用base R更容易

as.data.frame(as.table(m1))
  Var1 Var2 Freq
1    X    A    1
2    Y    A    2
3    Z    A    3

数据

m1 <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))
8mmmxcuj

8mmmxcuj2#

as.tibble可以将矩阵的rownames转换为列,然后可以使用gather()创建group2列:

library(tidyverse)

m <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))

newtib <- m %>%
    as.tibble(rownames = "group1") %>%
    gather('A', key = "group2", value = "value")

> newtib
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <int>
1 X      A          1
2 Y      A          2
3 Z      A          3

> tibble::tribble(~group1, ~group2, ~value, "X", "A", 1, "Y", "A", 2, "Z", "A", 3)
# A tibble: 3 × 3
  group1 group2 value
  <chr>  <chr>  <dbl>
1 X      A          1
2 Y      A          2
3 Z      A          3
z5btuh9x

z5btuh9x3#

1.将矩阵转换为 Dataframe
1.将行名带到group1
1.突变group2

data.frame(matrix) %>% 
  rownames_to_column("group1") %>% 
  mutate(group2 = colnames(matrix)) %>% 
  dplyr::select(group1, group2, value=A)
group1 group2 value
1      X      A     1
2      Y      A     2
3      Z      A     3
lsmepo6l

lsmepo6l4#

你可以用-

library(tidyverse)

mat <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))

mat  %>%
  as.data.frame() %>%
  rownames_to_column(var = 'group1') %>%
  pivot_longer(cols = -group1, names_to = 'group2')

#  group1 group2 value
#  <chr>  <chr>  <dbl>
#1 X      A          1
#2 Y      A          2
#3 Z      A          3
fbcarpbf

fbcarpbf5#

我会选

m <- matrix(1:3, nrow = 3, dimnames = list(c("X","Y","Z"), c("A")))
tibble(
    group1 = rownames(m)[row(m)]
    ,group2 = colnames(m)[col(m)]
    ,value = c(m)
)

其中:

  • 推广到多列的情况
  • 对于大矩阵来说会很快
  • 很简单
j5fpnvbx

j5fpnvbx6#

你还有两个基本的R选项

> as.data.frame.table(mat)
  Var1 Var2 Freq
1    X    A    1
2    Y    A    2
3    Z    A    3

> cbind(expand.grid(dimnames(mat)), mat)
  Var1 Var2 A
X    X    A 1
Y    Y    A 2
Z    Z    A 3

数据

mat <- matrix(1:3, nrow = 3, dimnames = list(c("X", "Y", "Z"), c("A")))

相关问题