R-使用函数过滤向量 [英] R - Filter a vector using a function

查看:24
本文介绍了R-使用函数过滤向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有与此功能相似的功能:

I have a function similar to this one:

isGoodNumber <- function(X) 
{
if (X==5) return(TRUE) else return(FALSE)
}

I have a vector:
v<-c(1,2,3,4,5,5,5,5)

我想获得一个包含 v 元素的新向量,其中 isGoodNumber(v)== TRUE

I want to obtain a new vector that contains the elements of v where isGoodNumber(v) == TRUE

我该怎么做?

尝试了 v [isGoodNumber(v)== TRUE] ,但是它不起作用:-)

Tried v [ isGoodNumber(v) == TRUE ] but it doesn't work :-)

谢谢!

推荐答案

您需要

You'll need to Vectorize the function to call it on a vector:

isGoodNumber = Vectorize(isGoodNumber)
v[isGoodNumber(v)]

这篇关于R-使用函数过滤向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆