In gtsummary, is there a way to add add_n() on the side of the variable's label? (instead of in a new column)

huangapple go评论65阅读模式
英文:

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()

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 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()

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 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()

In gtsummary, is there a way to add add_n() on the side of the variable's label? (instead of in a new column)

创建于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 &lt;- function(.data, ...){
  nv &lt;- apply(.data, 2, function(x)sum(!is.na(x)))
  newnames &lt;- paste(colnames(.data), &quot; (N=&quot;, nv, &quot;)&quot;, sep=&quot;&quot;)
  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 %&gt;% 
  select(mpg, disp, vs) %&gt;% 
  add_n_name() %&gt;%   
  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>

huangapple
  • 本文由 发表于 2023年2月24日 06:49:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551112.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定