Indicator function in R

2020-02-12 05:25发布

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.

标签: r function
4条回答
叼着烟拽天下
2楼-- · 2020-02-12 05:53

The I function in R, called the Inhibit Interpretation/Conversion of Objects function, can be used for this purpose. For instance, the line below returns the values for the function I(x < 4) where X = {0, 1, 2, 3, 4, 5}:

> I(0:5 < 4)
[1]  TRUE  TRUE  TRUE  TRUE FALSE FALSE

In R TRUE and FALSE can be treated as 1 and 0s, but if you insist on your output being precisely those numbers, just wrap your I function into as.numeric.

查看更多
Luminary・发光体
3楼-- · 2020-02-12 06:09

There is also an built-in indicator function in R

Indicator(x,min,max)

-Inf and Inf are still the valid values.

查看更多
地球回转人心会变
4楼-- · 2020-02-12 06:12

There are a variety of ways, the minimal keystroke one:

  Ivec <- 0+(vec>0)

Saves a couple of keystrokes over: as.numeric(vec>0). I would guess the ifelse(x>0,1,0)-approach would be somewhat slower if applied to a large vector or if used in simulations. Could also use:

 Ivec <- 1*(vec>0)
查看更多
▲ chillily
5楼-- · 2020-02-12 06:15

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

查看更多
登录 后发表回答