整数列的总和是 double

Sum of integer columns is double

我不明白为什么以及如何防止两个整数列的总和为 class numeric,请键入 double。有什么想法吗?

这是一个小的工作示例

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" 

由于 rowSums() 将始终 return 键入双精度,您也可以将 Reduce()+ 运算符结合使用以 return 新列作为integer

mydt[,C:=Reduce(`+`, lapply(.SD, function(x) ifelse(!is.na(x),x,0))),.SDcols = c("A","B")]