限制数据帧(R)中的小数位数 [英] Limiting the number of decimals in a dataframe (R)
问题描述
我想限制导入数据帧时的小数位数.我的.txt输入在值"列的每一行都有16个小数.我的数据框看起来像这样:
I would like to limit the number of decimals when a data frame is imported. My .txt input have 16 decimals to each row in collumn "Value". My dataframe look like that:
Value
0.202021561664556
0.202021561664556
0.202021561664556
0.202021561664556
...
我期望的数据框
Value
0.20202156
0.20202156
0.20202156
0.20202156
...
无效的实际输入(DF):
Real input (DF) that not works:
DF <- "NE001358.Log.R.Ratio
-0.0970369274475688
0.131893549586039
0.0629266495860389
0.299559132381831
-0.0128804337656807
0.0639743960526874
0.0271669351886552
0.322395363972391
0.179591292893632"
DF <- read.table(text=DF, header = TRUE)
推荐答案
对于数字列,此处 is.num
为 TRUE
,否则为 FALSE
.然后,我们将 round
应用于数字列:
Here is.num
is TRUE
for numeric columns and FALSE
otherwise. We then apply round
to the numeric columns:
is.num <- sapply(DF, is.numeric)
DF[is.num] <- lapply(DF[is.num], round, 8)
如果您的意思不是您需要更改数据框,而是只想将数据框显示为8位数字,那么它就是:
If what you meant was not that you need to change the data frame but just that you want to display the data frame to 8 digits then it's just:
print(DF, digits = 8)
在dplyr 1.0.0及更高版本中,可以像这样在 mutate
中使用 across
:
In dplyr 1.0.0 and later one can use across
within mutate
like this:
library(dplyr)
DF %>% mutate(across(is.numeric, ~ round(., 8)))
这篇关于限制数据帧(R)中的小数位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!