Home > Enterprise >  Sequentially subsetting a data.frame from its columns
Sequentially subsetting a data.frame from its columns

Time:12-02

I need to subset in R the following data.frame keeping only the rows for which the value in column 2 is greater than the value in column 1 but lower than the value in column 3.

seq1 = seq(0, 1, by = 0.25)
ncol = 3
df = expand.grid(rep(list(seq1), ncol))

I know that I can do as follows

df = df[df$Var1 < df$Var2 & df$Var2 < df$Var3,]

However, I need this code line to work in a package where the number of columns, ncol, is not fixed. How can I solve it?

CodePudding user response:

With rowSums:

df[rowSums(df[,-ncol(df)] < df[,-1]) == ncol(df) - 1,]
#>     Var1 Var2 Var3
#> 56  0.00 0.25 0.50
#> 81  0.00 0.25 0.75
#> 86  0.00 0.50 0.75
#> 87  0.25 0.50 0.75
#> 106 0.00 0.25 1.00
#> 111 0.00 0.50 1.00
#> 112 0.25 0.50 1.00
#> 116 0.00 0.75 1.00
#> 117 0.25 0.75 1.00
#> 118 0.50 0.75 1.00
  • Related