如何在将数值覆盖为整数时避免引入NA

时间:2016-08-09 08:31:10

标签: r

这是我的数据

mydata <- structure(list(GroupA_1 = c(400730000, 0, 0, 0, 4442200000, 0, 
0, 0, 0, 4482700000, 0, 0, 0, 0, 0), GroupA_2 = c(375840000, 
0, 0, 38008000, 7963200000, 0, 0, 0, 164980000, 4102700000, 0, 
0, 0, 0, 89135000), GroupA_3 = c(342230000, 0, 0, 0, 6705700000, 
14662000, 0, 0, 0, 4.665e+09, 0, 0, 0, 0, 0), GroupA_4 = c(311840000, 
0, 0, 0, 4611900000, 0, 0, 0, 148700000, 5108300000, 0, 0, 0, 
0, 123910000)), .Names = c("GroupA_1", "GroupA_2", "GroupA_3", 
"GroupA_4"), class = "data.frame", row.names = c("first1", "first2", 
"first3", "first4", "first5", "first6", "first7", "first8", "first9", 
"first10", "first11", "first12", "first13", "first14", "first15"
))

我像这样加载数据

mydata <- read.table("path to mydata.txt", header=TRUE, row.names = 1)

然后我str it它,我看到值是数字

'data.frame':   15 obs. of  4 variables:
 $ GroupA_1: num  4.01e+08 0.00 0.00 0.00 4.44e+09 ...
 $ GroupA_2: num  3.76e+08 0.00 0.00 3.80e+07 7.96e+09 ...
 $ GroupA_3: num  3.42e+08 0.00 0.00 0.00 6.71e+09 ...
 $ GroupA_4: num  3.12e+08 0.00 0.00 0.00 4.61e+09 ...

我尝试将它们转换为如下所示的整数

mydata2 <- data.frame(sapply(mydata, as.integer))

将NA引入数据

Warning messages:
1: In lapply(X = X, FUN = FUN, ...) :
  NAs introduced by coercion to integer range
2: In lapply(X = X, FUN = FUN, ...) :
  NAs introduced by coercion to integer range
3: In lapply(X = X, FUN = FUN, ...) :
  NAs introduced by coercion to integer range
4: In lapply(X = X, FUN = FUN, ...) :
  NAs introduced by coercion to integer range

如何在不引入NA的情况下将数据转换为整数?因为我认为没有任何理由有NA

1 个答案:

答案 0 :(得分:1)

编辑:

R仅限于小于2147483648的整数。请参阅struggling with integers (maximum integer size)

您的命令适用于较小的数字:

mydata2 <- mydata/1000
mydata3 <- data.frame(sapply(mydata2, as.integer))
str(mydata3)

'data.frame':   15 obs. of  4 variables:
 $ GroupA_1: int  400730 0 0 0 4442200 0 0 0 0 4482700 ...
 $ GroupA_2: int  375840 0 0 38008 7963200 0 0 0 164980 4102700 ...
 $ GroupA_3: int  342230 0 0 0 6705700 14662 0 0 0 4665000 ...
 $ GroupA_4: int  311840 0 0 0 4611900 0 0 0 148700 5108300 ...