问问题
35176 次
4 回答
19
I'd use which
to get the vector of rows numbers from which you can sample
given your condition....
iris[ sample( which( iris$Species != "setosa" ) , 2 ) , ]
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#59 6.6 2.9 4.6 1.3 versicolor
#133 6.4 2.8 5.6 2.2 virginica
于 2013-11-14T22:29:22.370 回答
11
With dplyr:
library(dplyr)
set.seed(12)
filter(iris, Species != "setosa") %>% sample_n(., 2)
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
7 6.3 3.3 4.7 1.6 versicolor
81 7.4 2.8 6.1 1.9 virginica
于 2015-07-05T08:41:32.870 回答
4
It'd be cleaner to not do it in one line, but
iris[iris$Species != "setosa",][sample(nrow(iris[iris$Species != "setosa",]), 2), ]
于 2013-11-14T22:07:19.933 回答
4
Clean and simple data table approach:
require(data.table)
iris <- data.table(iris)
cond <- iris[Species!= 'setosa', which = T]
iris[sample(cond, 2)]
于 2013-11-14T22:25:01.577 回答