AliCivil
AliCivil

Reputation: 2053

R as.numeric in a formula

I have the following data frame:

id<-c(1,2,3,4)
x<-c(0,2,1,0)
A<-c(1,3,4,3)
df<-data.frame(id,x,A)

now I want to make a variable called value in a way that if x>0, value for each id would be equal to A+1/x, and if x=0, value would be equal to A. with this aim I have typed

value <- df$A + as.numeric(df$x > 0)*(1/df$x)

what I expect is a vector a follows:

[1] 1 3.5 5.0 3

however what I get by typing the above command is :

 [1] NaN 3.5 5.0 NaN  

I wonder if anyone can help me with this problem. Thanks in advance!

Upvotes: 1

Views: 349

Answers (1)

plannapus
plannapus

Reputation: 18749

I think it would be simpler to use function ifelse in this case:

ifelse(df$x>0, df$A + (1/df$x), df$A)
[1] 1.0 3.5 5.0 3.0

See ?ifelse for more details.

With the command you were trying to apply, although as.numeric(df$x>0) was indeed giving you a vector of 1 and 0 (so it was a good idea), it didn't change the fact that 1/df$x was an NaN when df$x was equal to 0 (since you can not divide by 0).

Upvotes: 4

Related Questions