英文:
In gtsummary, is there a way to add add_n() on the side of the variable's label? (instead of in a new column)
问题
I would like to add something like a (N = {N}) next to the name of each variable but in the same column, is there any default option for this?
library(gtsummary)
library(dplyr)
mtcars %>% select(mpg, disp, vs) %>% tbl_summary() %>% add_n()
I looked for a solution on the package's official website but didn't find anything (english is not my native language :/)
英文:
I would like to add something like a (N = {N}) next to the name of each variable but in the same column, is there any default option for this?
library(gtsummary)
library(dplyr)
mtcars %>% select(mpg, disp, vs) %>% tbl_summary() %>% add_n()
I looked for a solution on the package's official website but didn't find anything (english is not my native language :/)
答案1
得分: 1
我不知道是否存在 gtsummary
中的方法,但你可以创建一个小函数来执行这个操作:
library(gtsummary)
library(dplyr)
add_n_name <- function(.data, ...){
nv <- apply(.data, 2, function(x)sum(!is.na(x)))
newnames <- paste(colnames(.data), " (N=", nv, ")", sep="")
setNames(.data, newnames)
}
函数 add_n_name()
接受数据,计算每个变量的非缺失观察数量,通过将 (N={N})
粘贴到变量名称中创建新名称,然后将数据集的名称设置为包含 N 的这些新名称。将其放在选择要使用的变量之后:
mtcars %>%
select(mpg, disp, vs) %>%
add_n_name() %>%
tbl_summary()
创建于2023-02-23,使用 reprex v2.0.2
英文:
I don't know if there's a way in that exists in gtsummary
, but you could make a little function that would do it for you:
library(gtsummary)
library(dplyr)
add_n_name <- function(.data, ...){
nv <- apply(.data, 2, function(x)sum(!is.na(x)))
newnames <- paste(colnames(.data), " (N=", nv, ")", sep="")
setNames(.data, newnames)
}
The function add_n_name()
, takes the data, calculates the number of non-missing observations for each variable, creates new names by pasting (N={N})
to the variable name and then sets the names of the dataset to these new names that contain N. Stick this in your pipeline after you select the variables you are going to use:
mtcars %>%
select(mpg, disp, vs) %>%
add_n_name() %>%
tbl_summary()
<img src="https://i.stack.imgur.com/zzPPG.png" width="400"/>
<sup>Created on 2023-02-23 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论