简体   繁体   中英

maximum function in R removes decimals

I have a question according to the max function in R. I have a column in a dataframe which has 2 decimals after the comma and whenever I apply the max function on the column i will get the highest value but with only 1 decimal after the comma.

max(df$e)

How can I get two decimals after the comma? I tried using options() and round() but nothing works.

Reproducible example:

a = c(228, 239)
b = c(50,83)
d = c(0.27,0.24) 
e = c(2.12,1.69)
df = data.frame(a,b,d,e)

max(df$e)
#[1] 2.1

df
#   a    b    d   e
# 1 228 50 0.27 2.1
# 2 239 83 0.24 1.7

Now I would like to make more calculations:

df$f = (sqrt(df[,1]/(df[,2]+0.5))/max(df$e))*100

In the end the dataframe should have column a and b without decimals and d , e and f with two decimals after the comma.

Thank you!

tl;dr you've probably got options(digits = 2) .

df
    a  b    d    e
1 228 50 0.27 2.12
2 239 83 0.24 1.69

If I set options(digits = 2) then R uses this value to set the output format (it doesn't change the actual values), globally, to two significant digits — this is "total digits", not "digits after the decimal point".

options(digits = 2)
df
    a  b    d   e   f
1 228 50 0.27 2.1 100
2 239 83 0.24 1.7  80

To restore the value to the default, use options(digits = 7) .

After restoring the default digits setting and computing df$f = (sqrt(df[,1]/(df[,2]+0.5))/max(df$e))*100 I get

    a  b    d    e        f
1 228 50 0.27 2.12 100.2273
2 239 83 0.24 1.69  79.8031

You can round the last column to two decimal places:

df$f <- round(df$f, 2)
> df
    a  b    d    e      f
1 228 50 0.27 2.12 100.23
2 239 83 0.24 1.69  79.80

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM