jeudi 22 octobre 2015

R: ifelse, return a subset based on a condition

I am still learning R and bumped into something that is beyond my comprehansion. I spent like 2 hours trying to figure it out on my own and failed :-( .

I have a data.frame (let's think of iris, for instance) that I want to subset using ifelse. If the 1st row is a "setosa", I want a data.frame back with first 50 rows, if not, the next 100 rows. See below.

data (iris)
a <- ifelse(iris$Species[1] == "setosa", iris[1:50,],iris[51:150,])

I would expect the above to return a subset of the original data.frame, but what I actually get is

[[1]]
 [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1 5.4 5.1 4.6
[24] 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8
[47] 5.1 4.6 5.3 5.0

I simply don't get it...

Aucun commentaire:

Enregistrer un commentaire