Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is error : Can't convert from <double> to <integer> due to loss of precision. in R

I have ran this piece of code before and never had an error.

 df.new <- df1

for(i in 1:nrow(df1)){
  df.new[j,] <- df1[j,]/df2$specificCol[j]
  
}
  

as a point example,

df1[1,1]/df2$specificCol[1] = 6.179306e-06

when I just manually want to set df.new[1,1] with this number, I get the error.

df.new[1,1] <-6.179306e-06

this time however I get this error

Error: Assigned data `6.179306e-06` must be compatible with existing data.
i Error occurred for column `x1`.
x Can't convert from <double> to <integer> due to loss of precision.
* Locations: 1.
Run `rlang::last_error()` to see where the error occurred.

how should I fix this error?

ps. thanks to @user20650, in case someone else needs this: it was enough to write as.data.frame(df.new) instead of df.new ( which turns back true for is.data.frame(df.new).
I do not know why but this worked!

like image 202
Mathica Avatar asked Sep 21 '25 11:09

Mathica


1 Answers

I don't know why this worked for you in the past and stopped working (perhaps there has been a change in the tidyverse that contains the tibble package, but I didn't run across anything obvious) but here's a short explanation of what's going wrong:

df = tibble::tibble(x=1L:2L)

If we select df[1,1] we get:

str(df[1,1])
# tibble [1 × 1] (S3: tbl_df/tbl/data.frame)
# $ x: int 1

That is, we get a 1x1 tibble with type integer. When we try to replace this element with a non-integer value (e.g. df[1,1] <- 1.2), R complains.

There are a few ways to work around this.

  • If we use [[-indexing rather than [, indexing, the [[-extraction gives us a vector rather than a tibble. df[[1]][1] <- 1.2 works, and coerces the whole column to a double (floating point) type.
  • df <- as.data.frame(df); df[1,1] <- 1.2 also works, because base-R data frames have different rules from tibbles; in particular df[,1] is a vector rather than a data frame
  • we could also explicitly convert the column to a double type; df[[1]] <- as.double(df[[1]]); df[1,1] <- 1.2 also works.

Basically, tibbles say that even when i is a single-element vector, df[,i] is always a one-column tibble rather than being downgraded to a vector, and it's fussy about replacing elements with elements of a different type (even though most of the time R is very lax about allowing you to interconvert between different data types when it makes sense).

like image 164
Ben Bolker Avatar answered Sep 23 '25 02:09

Ben Bolker