R Error Message: “error in cov.wt(z) : ‘x’ must contain finite values only”

As a programmer error messages are annoying, but they are part of knowing when you have a problem. The usefulness of the message varies greatly, and your understanding of the error message will be a great help. The “cov.wt(z) : ‘x’ must contain finite values only” error message may seem daunting at first, but make sense once you understand it.

When Would I See This Error?

This error occurs when using the cov.wt() function with a dataframe that contains one or more “NA” values. If you do not deal with them, it will trigger the error message.

> z = read.table(text = '
+ A B C D
+ 1 3 20 81 21
+ 2 4 34 13 22
+ 3 5 NA NA 23
+ 4 6 42 16 24
+ 5 7 65 26 25', header=TRUE)
> cov.wt(z)
Error in cov.wt(z) : 'x' must contain finite values only

This example has two “NA” values in the data frame. The result you see is our error message.

What Is Causing This Error?

This error is caused by the data frame you are using having “NA” values when the cov.wt() function is looking for numeric values. If this function encounters an “NA” value, it cannot do anything with it. The result is that it produces an error message.

> z = read.table(text = '
+ A B C D
+ 1 3 20 81 21
+ 2 4 34 13 22
+ 3 5 46 18 23
+ 4 6 42 16 24
+ 5 7 65 26 25', header=TRUE)
> cov.wt(z)

As you can see, this data frame has only numeric values and it works fine. This shows that the problem causing the error is the presence of the “NA” values in the data frame.

How To Fix This Error

Fixing this area is quite simple. All you need to do is eliminate the “NA” values. There are three simple ways that you can do this, however, they produce different results from the cov.wt() function.

dz=na.omit(z)
   cov.wt(dz)

The first one substitutes the above code for “cov.wt(z).” The na.omit() function removes every row that contains an “NA” value. This solution could be problematic if every row of your data frame contains a”NA” value. In this case, you will have no rows to enter into the cov.wt() function and it will return all zeros.

> for(y in 1:ncol(z)) {
+ for(x in 1:nrow(z)) {
+ if (is.na(z[x,y])) z[x,y] = 0
+ }}

Adding this code before “cov.wt(z)” is another way of fixing the error message. It equates all “NA” values to zero and thus finite values.

> dz = na.omit(z)
> for(y in 1:ncol(z)) {
+ for(x in 1:nrow(z)) {
+ if (is.na(z[x,y])) z[x,y] = mean(dz[,y])
+ }}

Adding this code before “cov.wt(z)” is our final way of fixing this error message. It equates all “NA” values to the column average and thus finite values. All three of these options will dynamically fix this error.

When working with data in r, even the most skilled programmers will run into issues and error messages. The good news is most of these error messages are easy to fix, and with a little help from your friends here at ProgrammingR, you’ll be running smoothly again in no time!

Scroll to top
Privacy Policy