How can I create a function in R that converts my p values as follows?
 If p>0.05 -> ns
 If p<0.05 -> 1
 If p<10-2 -> 2
 If p<10-3 -> 3
 If p<10-4 -> 4
 etc...
How can I create a function in R that converts my p values as follows?
 If p>0.05 -> ns
 If p<0.05 -> 1
 If p<10-2 -> 2
 If p<10-3 -> 3
 If p<10-4 -> 4
 etc...
We can use case_when to do a custom category
library(dplyr)
f1 <- function(pval) {
       case_when(pval > 0.5 ~ 'ns',
                 pval < 1e-4 ~ '4',
                 pval < 1e-3 ~ '3',
                 pval < 1e-2 ~ '2',
                 pval < 0.05 ~ '1'
                
                
                 )
      }
f1(c(0.04, 1.2,  0.00005))
#[1] "1"  "ns" "4"            
The @akrun answer is good if you only care to go down to 10e-4. A more general solution that follows the powers all the way down might be like the following:
# from here: https://stackoverflow.com/questions/6461209/how-to-round-up-to-the-nearest-10-or-100-or-x
roundUp <- function(x) 10^ceiling(log10(x))
categorize_p = function(ps) {
  logged = -log10(roundUp(ps))
  logged[ps > .05] = "ns"
  return(logged)
}
categorize_p(c(.1,.049, .001, .01))
#[1] "ns" "1"  "3"  "2"