0
我不明白爲什麼以及如何防止兩個整數列的和爲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"
除了修改表的NAS出來的,用'lapply(.SD,something_or_other)取代''.SD'應該工作,嗯。 – Frank
謝謝弗蘭克,好辦法! – mtoto