gpt4 book ai didi

R:ifelse,根据条件返回子集

转载 作者:行者123 更新时间:2023-12-03 00:39:06 28 4
gpt4 key购买 nike

我仍在学习 R,并遇到了一些超出我理解的事情。我花了大约 2 个小时试图自己解决这个问题,但失败了:-( 。

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

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

我希望上面返回原始 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

我根本不明白...

最佳答案

您可以在 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 是一个向量,它会返回一个向量,如果它是一个单一值,它会返回一个单一值等等。如果您提供错误的参数,它会产生垃圾结果。举个例子

> 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 的作用是遍历某个对象,并根据返回 TRUEFALSE 的某些 test 替换该对象中的值> 对于要替换的每个值。

关于R:ifelse,根据条件返回子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33275897/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com