Search code examples
rextractcriteria

How to extract values meeting a certain criterion


If you have a data frame, e.g.:

 D1 <-(DW$Ag, DW$Al, DW$As, DW$Ba)

*concentrations of elements

And you run a shapiro.test and the results are, e.g.:

             DW.Ag      DW.Al        DW.As     DW.Ba      
statistic 0.9030996  0.5204454    0.9761229 0.9286749  
p.value   0.01000898 8.873327e-09 0.7157865 0.04528581 

and you need to extract all p-values equal or below 0.5, how do you do it? I tried:

stat[stat$p.value <= 0.5, ]
stat[which(lres1$p.value <= 0.5), ]

(note: let's say the name of the results was STAT/list containing data..

Thanks in advance


Solution

  • A quick read of the help page for the shapiro test indicates that the object returned is a list item containing several objects, including the p-values.

    str(shapiro.test(rnorm(100, mean = 5, sd = 3)))
    

    So if you were to run the shapiro test on multiple columns of numeric data like:

    df <- data.frame(x1 = rnorm(100, mean = 5, sd = 3), x2 = rnorm(100, mean = 5, sd = 3), x3 = rnorm(100, mean = 5, sd = 3), x4 = rnorm(100, mean = 5, sd = 3))
    list <- lapply(df, shapiro.test)
    

    And inspect the results using str(). You would find the p-values for the 4 test run on this sample data.

    str

    Extract them out using some looping code, and you are good to go

    x <- unlist(lapply(list, `[`, 'p.value'))
    x[x <= 0.5]
    

    Hope that helps!