我有一个数据框,在数据中有NA。我可以轻松地将整列重新格式化为3位小数,而不考虑NA。但是,我无法找到完成整个数据帧的方法。没有比单独操作列更简单的方法吗?我也没有运气申请工作。
> ndf3
a b c d e
1 0.144346473029046 0.0945535269709544 0.127334024896266 0.125881659751037 0.108239419087137
2 0.1376 0.1489 0.0949 0.11784 0.1372
3 1.48794219374094 1.53595988141984 1.21977361926472 1.15852039195536 0.707774430272806
4 3.96992500677986 3.90772031563767 3.61382453467775 3.39967072835538 4.30292753254034
5 0.174889714039075 -0.419130501555829 0.113585656836338 -0.0307388258550179 -0.309314899645693
6 0.135682205983122 0.189426931757576 0.158335341568249 0.116675569765867 0.0645715900731325
252 37.8736196377026 22.0640317131964 33.4935080490794 33.2572127571306 29.0085133196937
8 0.335796353933727 0.179593968145971 0.484609677920302 NA NA
9 0.788381742738589 0.742738589211618 0.767634854771784 0.813278008298755 1
10 1.42703970549072 1.33470191247724 1.25827986596585 1.32419222712559 1
> class(ndf3)
[1] "data.frame"
> typeof(ndf3)
[1] "list"
> c <- format(round(as.numeric(as.character(ndf3)),3), nsmall = 3, na.encode = TRUE)
Warning message:
In format(round(as.numeric(as.character(ndf3)), 3), nsmall = 3, :
NAs introduced by coercion
> c
[1] "NA" "NA" "NA" "NA" "NA"
> is.character(ndf3)
[1] FALSE
> is.character(ndf3[[1]])
[1] TRUE
> round(as.numeric(ndf3[[1]]),3)
[1] 0.144 0.138 1.488 3.970 0.175 0.136 37.874 0.336 0.788 1.427
答案 0 :(得分:0)
如果您只想要舍入到3位数字:
ndf3 <- data.frame(lapply(ndf3, round, 3))
编辑:上述方法允许您将任何操作应用于整个data.frame。例如,强制数字然后舍入到3位数:
lapply(ndf3, function(x) round(as.numeric(x), 3))
或者如果您不想使用匿名功能,可以提前定义该功能。这相当于上面的内容:
forced_numeric_round3 <- function(x) round(as.numeric(x), 3)
lapply(ndf3, forced_numeric_round3)
答案 1 :(得分:0)
如果数据框中的每一列都是数字:as.data.frame(round(as.matrix(ndf3),3))