Linear model function lm() error: NA/NaN/Inf in foreign function call (arg 1)

风格不统一 提交于 2019-11-27 23:29:13

I know this thread is really old, but the answers don't seem complete, and I just ran into the same problem.

The problem I was having was because the NA columns also had NaN and Inf. Remove those and try it again. Specifically:

col2[which(is.nan(col2))] = NA
col2[which(col2==Inf)] = NA

Hope that helps your 18 month old question!

You should have a read the book A Beginner’s Guide to R for a complete explanation on this. Specifically, it mentions the following error:

Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok,...): NA/NaN/Inf in foreign function call (arg 4)

The solution is to add a small constant value to the Intensity data, for example, 1. Note that there is an on-going discussion in the statistical community concerning adding a small value. Be that as it may, you cannot use the log of zero when doing calculations in R.

I just suffered another possibility, after all posible na.omit and na.exclude checks.

I was taking something like:

lm(log(x) ~ log(y), data = ...)

Without noticing that, for some values in my dataset, x or y could be zero: log(0) = -Inf

So just another thing to watch out for!

Andrew

I solved this type of problem by resetting my options. options(na.action="na.exclude") or options(na.action="na.omit")

I checked my settings and had previously changed the option to "na.pass" which didn't drop my y observations with NAs (where y~x).

Try changing the type of col2 (and all other variables)

col2 <- as.integer(col2)

I just encountered the same problem. get the finite elements using

finiteElements = which(is.finite(col3*col4))
finiteData = data[finiteElements,]
lm(col2~col3*col4,na.action=na.exclude,data=finiteData)

I encountered this error when my equivalent of col2 was an integer64 rather than an integer and when using natural and polynomial splines, splines::bs and splines:ns for example:

m.fit <- lm(col1 ~ ns(col2))
m.fit <- lm(col1 ~ bs(col2, degree = 3))

Converting to a standard integer worked for me:

m.fit <- lm(col1 ~ ns(as.integer(col2)))
m.fit <- lm(col1 ~ bs(as.integer(col2), degree = 3))

I got this error when I inverted the arguments when calling reformulate and use the formula in my lm call without checking, so I had the wrong predictor and response variable.

Another thing to watch out for is using functions like log() or sin() make your x's and y's inf. eg. log 0 = 0 or sin(pi) = 0.

Make sure you don't have any 0 in your dependent variable.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!