Q:

NaNs produced when taking log to numbers greater than 0

I want to make a log variable to a variable over total assets. I do like this:
`HRSdata2$h1logass <- (ifelse(HRSdata2$h1atotb > 0, log(HRSdata2$h1atotb), 0))`

and I get the error message: In log(HRSdata2$h1atotb) : NaNs produced
My dataset shows that I get NA's when taking log(NA) which I predicted, BUT, why do I get NaN's? They concerne me a great deal more.
Also can someone show me the code for running a loop or other smart way to apply log to a bunch of columns? Currently this is my (very poor I know) code:
HRSdata2$h1logass <- (ifelse(HRSdata2$h1atotb > 0, log(HRSdata2$h1atotb), 0))
HRSdata2$h2logass <- (ifelse(HRSdata2$h2atotb > 0, log(HRSdata2$h2atotb), 0))
HRSdata2$h3logass <- (ifelse(HRSdata2$h3atotb > 0, log(HRSdata2$h3atotb), 0))
HRSdata2$h4logass <- (ifelse(HRSdata2$h4atotb > 0, log(HRSdata2$h4atotb), 0))
HRSdata2$h5logass <- (ifelse(HRSdata2$h5atotb > 0, log(HRSdata2$h5atotb), 0))
HRSdata2$h6logass <- (ifelse(HRSdata2$h6atotb > 0, log(HRSdata2$h6atotb), 0))
HRSdata2$h7logass <- (ifelse(HRSdata2$h7atotb > 0, log(HRSdata2$h7atotb), 0))
HRSdata2$h8logass <- (ifelse(HRSdata2$h8atotb > 0, log(HRSdata2$h8atotb), 0))
HRSdata2$h9logass <- (ifelse(HRSdata2$h9atotb > 0, log(HRSdata2$h9atotb), 0))
HRSdata2$h10logass <- (ifelse(HRSdata2$h10atotb > 0, log(HRSdata2$h10atotb), 0))

I basically just need to learn how to loop over variable names thanks.

A:

When you do ifelse(x > 0, log(x), 0), R computes log(x):
> x <- c(2, -1, 3)
> ifelse(x > 0, log(x), 0)
[1] 0.6931472 0.0000000 1.0986123
Warning message:
In log(x) : NaNs produced

But in the result you don't get the NaN, you get 0 for the values corresponding to x <= 0.
This ifelse statement is equivalent to
ifelse(c(TRUE, FALSE, TRUE), c(log(2), log(-1), log(3)), c(0,0,0))

R does not drop the calculations of the values of the second argument for which the value of the first argument is FALSE.

