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"))
Store the matrix in a list and convert it into a dataframe using map
command.
list_df <- list(T1, T2, T3)
dat <- purrr::map_df(list_df, as.data.frame, .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
With data.table
library(data.table)
list_df <- list(T1, T2, T3)
rbindlist(lapply(list_df, as.data.frame), idcol = 'group')
Or using base R
lst1 <- mget(str_c('T', 1:3))
out <- do.call(rbind, Map(cbind, group = seq_along(lst1), lst1))
and apply the as_tibble
once
as_tibble(out)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.