r - 如何构建矩阵或表格
问题描述
我有 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]
解决方案
你可以这样做:
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)
指示的代码
推荐阅读
- typescript - 如何在 Vue 组件上声明 Vuex 绑定的类型?
- testing - 使用 jmeter 进行移动应用程序测试,配置代理设置后互联网连接不起作用
- powershell - 使用 Get-AzureADUser 在 PowerShell 中删除具有特定域的完整电子邮件
- opencv - 不支持标签数据类型 = 19
- vue.js - 在 nuxt.js 中包含引导程序
- android - 使用 ArrayList 创建 Intent
- batch-file - 用批处理文件打开2个程序,我自己退出另一个程序后如何杀死一个程序?
- javascript - 避免使用 Javascript 重新加载页面的链接
- r - 使用列数不确定的 replace_na()
- python - Pandas - 不同时间窗的移动平均线