4

Consider the P-values from these two t-tests

set.seed(1)
x <- c(rnorm(50,1), rnorm(50, 2))
y <- (c(rep("a", 50), rep("b", 50)))

t.test(x ~ y)$p.value

[1] 1.776808e-07

set.seed(2)
x <- c(rnorm(50), rnorm(50))
y <- (c(rep("a", 50), rep("b", 50)))

t.test(x ~ y)$p.value

[1] 0.3922354

The first P value is <0.001 and the second is >0.001. If the P value happens to be <0.001, can I get R to print out the P value as <0.001. If the P value happens to be >0.001, can I get R to print out the actual P value? So the result of the first t-test should be printed as "<0.001" and the result of the second t-test should be printed as 0.3922354.

I am using knitr to convert R code to latex for my thesis. My rule is only P value >0.001 should be printed as actual P values.

luciano
  • 13,158
  • 36
  • 90
  • 130

1 Answers1

5

Just use an if statement:

p_val <- t.test(x,y)$p.value;
if(p_val>=0.001) {
  print(p_val)
} else {
  print("<0.001")
}
Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
  • Martin Dinov: that doesn't achieve what I need. I still need P value to be printed if <0.001, but I need it printed as "<0.001". – luciano Feb 09 '14 at 11:13
  • Ok, so just add the else case. See the updated answer. – Martin Dinov Feb 09 '14 at 11:15
  • 5
    Thanks should have thought of an ifelse type statement. Think this might be more compact within a latex document: `P <- t.test(x ~ y)$p.value; ifelse(P > 0.001, P, "<0.001")` – luciano Feb 09 '14 at 11:19
  • 2
    @luciano, unless P is a greater than 1 length vector, there is nothing wrong with `if(P > 0.001) P else "<0.001"`, and one could argue it is safer as it will throw a warning if the vector is unexpectedly longer than one. – BrodieG Feb 09 '14 at 15:07