IF/THEN Statement to calculate a proportion based on whether the variable is less than a number throws an error

50 Views Asked by At

From my variable in column 1 from the pval data, I want to sum all the pval that are less than 0.05 and find the proportion by dividing that sum by 10000 because my sample size is 10000.
I keep getting the error that the condition has length >1.

I have tried this:

if (pval[,1]<0.05)
{
  p1prop<-sum(pval[,1])/10000
}

and this:

if (pval[,1]<0.05)
{sum(pval[,1])/10000
}

How can I correct this?

2

There are 2 best solutions below

0
Elin On

If you literally just want the proportion this will work:

p1prop <- sum(pval[,1] < .05)/10000

What that is doing is first creating a logical vector (TRUE if the condition is true, FALSE if it is not). Then, since TRUE will be treated as 1 and false will be treated as 0, add them up.

0
Jay Bee On

You could do this:

# Load required library.

library(tidyverse)

# Set seed and create example data.

set.seed(123)

pval <- data.frame(value = runif(10000, min = 0.01, max = 0.1))

# Filter values less than 0.05 and calculate proportion.

pval %>% 
  filter(value < 0.05) %>% 
  count() / 10000