简体   繁体   English

避免在 dplyr 中重复 as_tibble()

[英]Avoid repeating as_tibble() in dplyr

Currently, I'm using multiple as_tibble(a_matrix) commands in my last line of code.目前,我在最后一行代码中使用了多个as_tibble(a_matrix)命令。 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.将矩阵存储在列表中,并使用map命令将其转换为 dataframe。

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.tabledata.table

library(data.table)
list_df <- list(T1, T2, T3) 
rbindlist(lapply(list_df, as.data.frame), idcol = 'group')

Or using base R或使用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一次

as_tibble(out)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM