-1

In my data frame, I have a lot of logical variables and I want to split the data frame into multiple subsets conditional on each logical variable is TRUE. For example, let's suppose this is my df:

     V1    V2    V3 V4
1  TRUE  TRUE FALSE  2
2  TRUE FALSE  TRUE  5
3 FALSE  TRUE FALSE  4

So I want to have three subsets:

[1]
     V1    V2    V3 V4
1  TRUE  TRUE FALSE  2
2  TRUE FALSE  TRUE  5

[2]
     V1    V2    V3 V4
1  TRUE  TRUE FALSE  2
2 FALSE  TRUE FALSE  4

[3]
     V1    V2    V3 V4
1  TRUE FALSE  TRUE  5

Thanks for any help!

mutian
  • 77
  • 1
  • 7
  • "suppose this is my df" -- not possible since `data.frame(V = c(T, T, F))` does not print like T T F. Please see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 for some guidance on writing code that makes an easily-reproduced example. – Frank Apr 07 '17 at 20:19

2 Answers2

0

A simple lapply loop should do the trick:

read.table(textConnection("V1 V2 V3 V4
T  T  F  2
T  F  T  5
F  T  F  4"), header=T) -> df

lapply(1:(ncol(df)-1), function(i) {
    subset(df, df[[i]])
})

[[1]]
    V1    V2    V3 V4
1 TRUE  TRUE FALSE  2
2 TRUE FALSE  TRUE  5

[[2]]
     V1   V2    V3 V4
1  TRUE TRUE FALSE  2
3 FALSE TRUE FALSE  4

[[3]]
    V1    V2   V3 V4
2 TRUE FALSE TRUE  5
thc
  • 9,527
  • 1
  • 24
  • 39
-1

Your problem is very simple. For the first subset you can use:

subset1 <- df[df[ ,1]==T, ]

in which the function takes out the rows that has the first column V1's value of T.

Of course if you wanna set up a whole function for that job for later use, then @thc's solution is best. But in case you just need to get 3 subsets nicely and quickly, try the above.

I'll let you figure out how to do the rest with subset2 and subset3.

AnodeHorn
  • 1
  • 4