将 p 值替换为 R 中数据框中的星星

Substitute p values for stars in data frame in R

我有一个 data.frame dfPSpearman_p 包含 p 值(数字数据)。我想用它们代替 p 值摘要星。我使用此代码:

 dfP$Spearman_p[dfP$Spearman_p < 0.0001] <- "****"
 dfP$Spearman_p[dfP$Spearman_p < 0.001] <- "***"
 dfP$Spearman_p[dfP$Spearman_p < 0.01] <- "**"
 dfP$Spearman_p[dfP$Spearman_p < 0.05] <- "*"
 dfP$Spearman_p[dfP$Spearman_p > 0.05] <- "ns"

但是,这会将 所有 p 值 <0.05(因此那些 <0.01)更改为 *(一颗星)。

我怀疑 R 在后续步骤中将 **** 视为 <0.05 的数字。那是对的吗?如果是这样,请问我该如何规避?

谢谢。

一旦进行了第一个替换,就将向量 dfP$Spearman_p 转换为字符向量。当比较字符向量 "***"(或任意数量的星星)小于 0.05 时,表达式被计算为 TRUE 并且 "***""*" 代替。

另请参阅:Why doesn't comparison between numeric and character variables give a warning?

我建议创建一个新列,即 Spearman_p_sign

dfP$Spearman_p_sign <- "ns"
dfP$Spearman_p_sign[dfP$Spearman_p < 0.0001] <- "****"
dfP$Spearman_p_sign[dfP$Spearman_p < 0.001] <- "***"
dfP$Spearman_p_sign[dfP$Spearman_p < 0.01] <- "**"
dfP$Spearman_p_sign[dfP$Spearman_p < 0.05] <- "*"

或者您可以使用嵌套的 ifelse,或 dplyr 包中的 case_when 函数。

尝试使用以下函数。它一次性改变了整个向量。

makeStars <- function(x){
  stars <- c("****", "***", "**", "*", "ns")
  vec <- c(0, 0.0001, 0.001, 0.01, 0.05, 1)
  i <- findInterval(x, vec)
  stars[i]
}

dfP$Spearman_p <- makeStars(dfP$Spearman_p)

但是,如果您创建一个新的矢量可能会更好。

dfP$Spearman_p_stars <- makeStars(dfP$Spearman_p)

我发现这个问题很有趣,因为 Ops 组在与 <= 一起使用时具有独特的行为。

比较 character 变量和 numeric 变量通常会产生 FALSE,例如:

> "a" < 1
[1] FALSE
> "a" < 10
[1] FALSE
> "a" < 100
[1] FALSE

但是,意识到运算符(Ops 组)并非如此。例如

> "*" < 1
[1] TRUE
> "*" < 10
[1] TRUE
> "*" < 100
[1] TRUE
> "*" < 0.1
[1] TRUE

不知道为什么 "*" 仍然 returns 一个 character..

> "+" < 0.1
[1] TRUE
> "+" < 100
[1] TRUE

Rui Barradas 的解决方案有效,这是您可以做的另一种方法,首先转换为字母,然后将字母转换为 *

test <- data.frame(col1 = c("A", "B", "C"), 
                   col2 = c(0.04, 0.009, 0.0009), stringsAsFactors = FALSE)

test$new[test$col2 < 0.05] <- "a"
test$new[test$col2 < 0.01] <- "aa"
test$new[test$col2 < 0.001] <- "aaa"

test$new2 <- gsub("a", "*", test$new)

  col1   col2 new new2
1    A 0.0400   a    *
2    B 0.0090  aa   **
3    C 0.0009 aaa  ***

另一种选择:使用 gtools 包中的 stars.pval()

Documentation here.