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!
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.
[[
-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 framedf[[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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With