Search code examples
rdataframeloopsdplyrtibble

Avoid repeating as_tibble() in dplyr


Currently, I'm using multiple as_tibble(a_matrix) commands in my last line of code. To avoid repeating this command, what would be the shortest alternative?

(T1 = matrix(c(2, 3, 5, 2, 3, 4, 4, 5), 4, 2))      
colnames(T1) <- c("y1", "y2")

(T2 = matrix(c(4:6, 8, 6, 7), 3, 2))      
colnames(T2) <- colnames(T1) 

(T3 = matrix(c(7, 8, 10, 9, 7, 6, 7, 8, 5, 6), 5, 2))      
colnames(T3) <- colnames(T1) 

# bind rows of T1,T2 & T3 score matricies for the 3 groups:
(dat <- bind_rows(as_tibble(T1), as_tibble(T2), as_tibble(T3), .id = "group"))

Solution

  • Store the matrix in a list and convert it into a tibble using map command.

    list_df <- list(T1, T2, T3)
    dat <- purrr::map_df(list_df, as_tibble, .id = 'group')
    dat
    
    #   group y1 y2
    #1      1  2  3
    #2      1  3  4
    #3      1  5  4
    #4      1  2  5
    #5      2  4  8
    #6      2  5  6
    #7      2  6  7
    #8      3  7  6
    #9      3  8  7
    #10     3 10  8
    #11     3  9  5
    #12     3  7  6