Reputation: 2233
I would like to filter out from a data frame all variables that have negative values. I used this line of code (below) to get the names of the columns but how can I save the positive columns with their data as a new data frame
dat <- read.table(text = " value jobs chairs tables lamps vases
-1 0 0 0 7 9
2 0 0 1 1 6
-3 0 1 0 3 5
4 0 1 1 7 8
-5 1 0 0 5 4
-6 1 0 1 1 3
7 1 1 0 0 7
8 1 1 1 6 6
9 0 0 0 8 9 ", header = TRUE)
names(dat)[sapply(dat, function(x) min(x))>=0]
[1] "value" "jobs" "chairs" "tables" "lamps" "vases"
Upvotes: 1
Views: 5883
Reputation: 903
Use the names you retrieved to subset your data frame:
myNames<-names(dat)[sapply(dat, function(x) min(x))>=0]
dat[,myNames]
Edit: if you don't need these names for later use:
dat[,sapply(dat, min)>=0]
Upvotes: 4
Reputation: 1513
or
dat[, sapply(dat, FUN = function(x) all(x >= 0))]
or
dat[, sapply(dat, FUN = function(x) !any(x < 0))]
Upvotes: 1