R中的指示功能 [英] Indicator function in R
问题描述
我在R中寻找一个指示函数,即一个返回1的函数,如果一个向量中元素的值大于0并返回零,如果向量中元素的值较小
我需要在一个向量中的所有元素上使用这个函数,返回一个只有零和一个新的向量。
Thanks。
如果我能够正确理解你,那么你想对整个数据框进行更改,假设我可以建议你像下面那样使用apply,其中df是你的数据框。
apply(df,2 ,函数(x)ifelse((x> 0),1,0))
如果它仅用于一个向量,如下所示:
x < - c(-2,3,1,0)
y< - ifelse(x> 0,1,0)
print(y)
[1] 0 1 1 0#输出
希望这有助于
I'm looking for an indicator function in R, i.e. a function that returns a 1, if the value of an element in a vector is greater than 0 and returns zero, if the value of an element in a vector is less than 0.
I need to use this function on all elements in a vector returning a new vector with only zeros and ones.
Thanks.
If i am able to understand you correctly then you want to make changes into entire data frame,assuming of which i can suggest you to use apply like below, where df is your data frame.
apply(df,2,function(x)ifelse((x>0),1,0))
You can also use if its for only one vector something like below:
x <- c(-2,3,1,0)
y <- ifelse(x>0,1,0)
print(y)
[1] 0 1 1 0 #Output
Hope this helps
这篇关于R中的指示功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!