You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为数据框系数添加显著性星号并格式化标准误差为括号形式

R语言数据框格式处理实现方法

先加载原始数据

df <- structure(list(rowname = c("Coefficient", "Standard error", "Observations", "75% Coefficient", "Standard error", "Observations", "125% Coefficient", "Standard error", "Observations", "Optimal Bandwidth", "75% Optimal Bandwidth", "125% Optimal Bandwidth"), tri = c(-0.127, 0.072, 436, -0.305, 0.088, 132, -0.133, 0.089, 281, 0.107, 0.047, 0.079), pvalue1 = c(0.078, NA, NA, 0.001, NA, NA, 0.135, NA, NA, NA, NA, NA), uni = c(0.064, 0.028, 444, 0.117, 0.023, 382, 0.043, 0.024, 560, 0.083, 0.138, 0.138), pvalue2 = c(0.023, NA, NA, 0, NA, NA, 0.07, NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA, -12L))

1. 定义显著性星号生成函数

根据p值规则生成对应星号并与系数拼接:

add_stars <- function(coef, p) {
  stars <- dplyr::case_when(
    p < 0.001 ~ "***",
    p < 0.01 ~ "**",
    p < 0.05 ~ "*",
    TRUE ~ ""
  )
  paste0(coef, stars)
}

2. 批量处理数据框

用dplyr一次性完成两个格式转换需求:

library(dplyr)

df_processed <- df %>%
  # 处理tri列:系数加星号、标准误差加括号
  mutate(tri = case_when(
    grepl("Coefficient", rowname) ~ add_stars(tri, pvalue1),
    grepl("Standard error", rowname) ~ paste0("(", tri, ")"),
    TRUE ~ as.character(tri)
  )) %>%
  # 处理uni列:系数加星号、标准误差加括号
  mutate(uni = case_when(
    grepl("Coefficient", rowname) ~ add_stars(uni, pvalue2),
    grepl("Standard error", rowname) ~ paste0("(", uni, ")"),
    TRUE ~ as.character(uni)
  )) %>%
  # 可选:移除不需要的p值列
  select(-pvalue1, -pvalue2)

处理后结果

运行print(df_processed, row.names = FALSE)会得到:

rowname       tri       uni
           Coefficient  -0.127*   0.064**
        Standard error  (0.072)   (0.028)
          Observations      436       444
       75% Coefficient -0.305*** 0.117***
        Standard error  (0.088)   (0.023)
          Observations      132       382
      125% Coefficient   -0.133    0.043*
        Standard error  (0.089)   (0.024)
          Observations      281       560
     Optimal Bandwidth     0.107     0.083
75% Optimal Bandwidth      0.047     0.138
125% Optimal Bandwidth     0.079     0.138

内容的提问来源于stack exchange,提问作者LearningR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:20:31