zca0
zca0

Reputation: 297

Calculate function in two different part

I have a vector y, which is a series of positive integers. For each value in y, I want to calculate:

How can I do that?

Upvotes: 0

Views: 84

Answers (3)

IRTFM
IRTFM

Reputation: 263381

It's very easy to do this with logical indexing:

z <- 1/y  # will have some Inf values but not throw an error
z[y==0] <- 0   # changes the Inf's to 0

Upvotes: 2

Sean
Sean

Reputation: 3955

Extending what Andrie has said to a matrix...

y <- matrix(1:25, ncol=5) # define the matrix y
z <- matrix(ifelse(y==1, 0, 1/y), ncol=ncol(y))

or I could just say

z <- matrix(ifelse(y==1, 0, 1/y), ncol=5)

Upvotes: 1

Andrie
Andrie

Reputation: 179448

Use ifelse and do it in one step:

y <- 1:5
z <- ifelse(y==1, 0, 1/y)

cbind(y, z)
     y         z
[1,] 1 0.0000000
[2,] 2 0.5000000
[3,] 3 0.3333333
[4,] 4 0.2500000
[5,] 5 0.2000000

Upvotes: 4

Related Questions