Converting matrix to tibble, adds matrix name to column, how do I fix the column name?

Hi all,

Stuck again, and I know this is going to be something simple.

I have a list containing 2 data frame class, 1 matrix class, and 1 character class. When I transform the matrix to a tibble, I am doing something wrong with the column names, and I can't figure it out. The real matrix has over 100 columns, so explicitly renaming the column won't work.

class(my_list) # list
is.object(my_list) # false

I extract the matrix simply with:

 my_matrix <- my_list$my_matrix

Reproducible example

# The matrix:
my_matrix <- matrix(c(59, 2), nrow = 2, ncol = 1, dimnames = list(c("ENSSSCG00000028996", "ENSSSCG00000005267"), c("26_Duodenum.bam")))
colnames(my_matrix) # Result: [1] "26_Duodenum.bam"

# Convert to tibble:
gene_counts <- tibble(gene = row.names(my_matrix), my_matrix)

# What I get: 
gene_counts           # column displayed as "my_matrix[,"26_Duodenum.bam"]"
colnames(gene_counts) # Result: [1] "gene"      "my_matrix"

# What I want:
gene_counts           # column displayed as "26_Duodenum.bam"
colnames(gene_counts) # Result: [1] "gene"      "26_Duodenum.bam"

Thanks in advance,

Kenneth

I think you need to use as_tibble().

library(tidyverse)

my_matrix <- matrix(c(59, 2), nrow = 2, ncol = 1, dimnames = list(c("ENSSSCG00000028996", "ENSSSCG00000005267"), c("26_Duodenum.bam")))
colnames(my_matrix) # Result: [1] "26_Duodenum.bam"
#> [1] "26_Duodenum.bam"
gene_count <- as_tibble(my_matrix, rownames = "gene")
colnames(gene_count)
#> [1] "gene"            "26_Duodenum.bam"
gene_count
#> # A tibble: 2 × 2
#>   gene               `26_Duodenum.bam`
#>   <chr>                          <dbl>
#> 1 ENSSSCG00000028996                59
#> 2 ENSSSCG00000005267                 2

Created on 2024-04-20 with reprex v2.0.2

2 Likes

Thank you. Knew it was something stupidly simple.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.