Alex
Alex

Reputation: 51

How to convert a matrix into a table in r

Suppose I have a matrix like this

> main<-matrix(c(1,4,5,7,NA,NA,NA,NA,3,6,12,3,45,NA,NA,NA,5,9,12,14,3,9,7,2),nrow=3,byrow = TRUE)
> main
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    4    5    7   NA   NA   NA   NA
[2,]    3    6   12    3   45   NA   NA   NA
[3,]    5    9   12   14    3    9    7    2

I want to create a table of 2 column and 3 rows Like this:


  Topic_no        Object/Transcript
  Topic 1          1, 4, 5, 7
  Topic 2          3, 6, 12, 3, 45
  Topic 3          5, 9, 12, 14, 3, 9, 7, 2

How can I do it?

Upvotes: 1

Views: 283

Answers (2)

TarJae
TarJae

Reputation: 79311

Here is a solution with unite from tidyr:

  1. matrix to tibble with as_tibble()
  2. use unite to unite all columns to one with arguement remove = TRUE
  3. Remove all characters after the last comma
  4. mutate Topic column
library(tidyr)
library(dplyr)
main %>% 
  as_tibble() %>% 
  unite(`Object/Transcript`, V1:V8, sep = ",", remove = TRUE) %>% 
  mutate(`Object/Transcript` = sub("(\\d)[^0-9]+$", "\\1", `Object/Transcript`)) %>%   
  mutate(Topic_no = paste0("Topic ", row_number()), .before=1)

Output:

  Topic_no `Object/Transcript`
  <chr>    <chr>              
1 Topic 1  1,4,5,7            
2 Topic 2  3,6,12,3,45        
3 Topic 3  5,9,12,14,3,9,7,2 

Upvotes: 1

akrun
akrun

Reputation: 887971

In base R, loop over the rows of the matrix with apply and MARGIN = 1, paste the non-NA elements as a string, create a two column data.frame with that along with a sequence column created for 'Topic_no'

data.frame(Topic_no = paste('Topic', seq_len(nrow(main))), 
        Object_Transcript =  apply(main, 1, function(x) 
            toString(x[complete.cases(x)])))

-output

 Topic_no        Object_Transcript
1  Topic 1               1, 4, 5, 7
2  Topic 2          3, 6, 12, 3, 45
3  Topic 3 5, 9, 12, 14, 3, 9, 7, 2

Upvotes: 2

Related Questions