首页 > 解决方案 > 如何构建矩阵或表格

问题描述

我有 4 个小 dfs,我想用它们来构建一个表/df。我尝试先将值输入矩阵,然后将其转换为 df。但是我的代码不起作用。而且我觉得我的方法可能不是一个好方法。有人可以指导我吗?也许如何首先构建正确的矩阵,然后可能是其他更好的方法来完成这项任务?非常感谢。

数据

T1<- structure(list(AESERYN = structure(c(1L, 2L, NA), .Label = c("N", 
"Y"), class = "factor"), pt_sae = c(12L, 1L, 1L)), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

T2<- structure(list(AESERYN = structure(1:2, .Label = c("N", "Y"), class = "factor"), 
    pt_sae = c(9, 0)), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

T3<- structure(list(AESERYN = structure(c(1L, 2L, NA), .Label = c("N", 
"Y"), class = "factor"), sae = c("62", "1", "1")), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

T4<-structure(list(AESERYN = structure(1:2, .Label = c("N", "Y"), class = "factor"), 
    sae = c("22", "0")), row.names = c(NA, -2L), class = c("tbl_df", 
"tbl", "data.frame"))

建立新的df(不工作):

test<-as.data.frame(matrix(c(unlist(T3[,"sae"]),
                              unlist(T4[,"sae"]),
                              unlist(T1[,"pt_sae"]),
                              unlist(T2[,"pt_sae"])),
                  ncol = 4, byrow = FALSE, 
                  dimnames = list(c("Non-Serious AE", 
                                    "Serious AE",
                                    "Unkonwn"),
                                  c("T3","T4","T1","T2"))))

结果应如下所示:

在此处输入图像描述

[![在此处输入图像描述][2]][2]

标签: r

解决方案


你可以这样做:

library(tidyverse)
mylist = list(T1 = T1, T2 = T2, T3 = T3, T4 = T4)

mylist %>%
  imap( ~set_names(.x, c(names(.x)[1], .y))) %>%
  reduce(full_join, by='AESERYN') %>%
  type.convert(as.is = TRUE) %>%
  mutate(AESERYN = recode(AESERYN,  
                    N = 'Non-Serious', Y = 'Serious', .missing = 'Unknown'),
         across(T1:T4, ~coalesce(.x, 0)))%>%
  column_to_rownames('AESERYN')

            T1 T2 T3 T4
Non-Serious 12  9 62 22
Serious      1  0  1  0
Unknown      1  0  1  0

请注意,您可以使用@akrunmget(paste0('T', 1:4)指示的代码


推荐阅读