Munrock
Munrock

Reputation: 423

Add count column to df based on multiple values

My dataframe looks like this:

p.vals          p.vals2         pvals3          
.006              1              .257
.25              .0002           .0178
.689             .0482           .117
.0027            .404            .0007

I want to add a fourth column that counts the values the meet the threshold pvalue of 0.05. Ideally I would end up with something like this:

p.vals          p.vals2         pvals3     count     
.006              1              .257        1
.25              .0002           .0178       2
.689             .0482           .117        1
.0027            .004            .0007       3

Is there an easy way to do this?

Upvotes: 0

Views: 31

Answers (1)

Mohamed Desouky
Mohamed Desouky

Reputation: 4425

Try this

library(dplyr)

df |> rowwise() |> mutate(count = sum(c_across() < .05))
  • output
# A tibble: 4 × 4
# Rowwise: 
  p.vals p.vals2 pvals3 count
   <dbl>   <dbl>  <dbl> <int>
1 0.006   1      0.257      1
2 0.25    0.0002 0.0178     2
3 0.689   0.0482 0.117      1
4 0.0027  0.004  0.0007     3
  • data
df <- tructure(list(p.vals = c(0.006, 0.25, 0.689, 0.0027), p.vals2 = c(1, 
2e-04, 0.0482, 0.004), pvals3 = c(0.257, 0.0178, 0.117, 7e-04
)), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 1

Related Questions