R: ifelse, return 基于条件的子集

R: ifelse, return a subset based on a condition

我还在学习R,遇到了一些我无法理解的东西。我花了大约 2 个小时试图自己弄清楚但失败了:-( .

我有一个 data.frame(例如,让我们想想鸢尾花),我想使用 ifelse 对其进行子集化。如果第一行是 "setosa",我想要一个 data.frame 返回前 50 行,如果不是,则返回接下来的 100 行。见下文。

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

我希望上面的内容 return 是原始 data.frame 的一个子集,但我实际得到的是

[[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

我就是不明白...

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

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

您可以在 ifelse 文档中阅读

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

所以如果 test 是一个向量,它 returns 一个向量,如果它是一个单一的值,它 returns 一个单一的值等等。如果你提供了错误的参数,它会产生垃圾结果。举个例子

> ifelse(1:10<5, 1, 0)
[1] 1 1 1 1 0 0 0 0 0 0
> ifelse(1:10<5, 0, 1:10)
[1]  0  0  0  0  5  6  7  8  9 10
> ifelse(TRUE, 1, 0)
[1] 1
> ifelse(TRUE, 1:10, 0)
[1] 1

在你的情况下你应该使用

if (condition) ... else ...

ifelseif ... else ...是不同的功能,ifelse不是另一个功能的单行。 ifelse 所做的是它遍历某个对象并根据某些 testeach[=37= 返回 TRUEFALSE 替换该对象中的值] 要替换的值。

上面给出了ifelse问题的答案。 然后根据你的实际应用,你也可以这样子化:

subset(iris, Species==Species[1])