I don't understand why and how to prevent the sum of two integer columns to be class numeric
, type double
. Any idea?
Here is a small working example
library(data.table)
set.seed(123)
A <- rnorm(20, 100, 5)
B <- rnorm(20, 50, 20)
NA.A <- which(A %in% sample(A, 5))
NA.B <- which(B %in% sample(B, 10))
zero.A<- which(A %in% sample(A, 3))
zero.B <- which(B %in% sample(B, 8))
A[NA.A] <- NA
A[zero.A] <- 0
B[NA.B] <- NA
B[zero.B] <- 0
mydt <- data.table(A = as.integer(A), B = as.integer(B))
sapply(mydt, class)
# A B
# "integer" "integer"
mydt[, C := rowSums(.SD, na.rm=T), .SDcols = c("A","B")]
sapply(mydt, class)
# A B C
# "integer" "integer" "numeric"
sapply(mydt, typeof)
# A B C
# "integer" "integer" "double"
As
rowSums()
will always return type double, you could alternatively useReduce()
in combination with the+
operator to return the new column asinteger
.