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

基于R语言:根据df2的p值为df1的相关系数添加显著性标记

解决方法

你可以通过嵌套ifelse生成对应星号标记,再和df1的系数拼接实现需求,具体步骤如下:

完整代码

# 示例数据
x=c(.05,.05,.05,.05,.05)
y=c(.05,.05,.05,.05)
z=c(.05,.05,.05)

max_ln <- max(c(length(x), length(y), length(z)))
df1 <- data.frame(col1 = c(x,rep(NA, max_ln - length(x))),
                  col2 = c(y,rep(NA, max_ln - length(y))),
                  col3 = c(z,rep(NA, max_ln - length(z))))

x2=c(.06,.05,.001,.0001,.07)
y2=c(.07,.05,.08,.001)
z2=c(.06,.04,.02)

max_ln2 <- max(c(length(x2), length(y2), length(z2)))
df2 <- data.frame(col1 = c(x2,rep(NA, max_ln2 - length(x2))),
                  col2 = c(y2,rep(NA, max_ln2 - length(y2))),
                  col3 = c(z2,rep(NA, max_ln2 - length(z2))))

# 生成星号标记
stars <- ifelse(df2 < 0.001, "***",
                ifelse(df2 < 0.01, "**",
                       ifelse(df2 < 0.05, "*", "")))

# 拼接系数与星号,处理NA值
result_df <- as.data.frame(
  matrix(
    ifelse(is.na(df1), NA, paste0(format(df1, digits = 3), stars)),
    nrow = nrow(df1),
    ncol = ncol(df1)
  )
)
colnames(result_df) <- colnames(df1)

# 查看结果
print(result_df)

代码说明

  • 嵌套ifelse从最严格的阈值(<0.001)开始判断,确保标记逻辑正确:p<0.001加***,p<0.01加**,p<0.05加*,其他情况无标记
  • format(df1, digits = 3)将系数格式化保留3位小数,输出更规范
  • 通过ifelse(is.na(df1), NA, ...)保留原数据中的NA值,避免被转为字符串"NA"
  • 最终结果转为data frame,保持和原数据一致的结构

运行结果

col1  col2  col3
1 0.050       0.050
2 0.050       0.050*
3 0.050**     0.050*
4 0.050*** 0.050** NA
5 0.050       NA

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 09:01:05