Reputation: 297
I have a vector y
, which is a series of positive integers. For each value in y
, I want to calculate:
z <- 1/y
, y
is 1 I need to set z
is zero.z
with zero for y
is 1 and 1/y
for y
is not 1.How can I do that?
Upvotes: 0
Views: 84
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
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
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