Lewwww
Lewwww

Reputation: 11

How to change number of decimal points depending on value in a column?

I want to mutate "Result" to have the same number of decimal points as "Limit". Here's the dataframe:

Limit Result
1 1.1
1.2 1.35
1.55 1.681

For example if Limit=1.2, I want to update Result from 1.35 to 1.4.

I first created the "Decimal" column by:

mutate(Decimal = nchar(file_ext(as.character(Limit))))
Limit Result Decimal
1 1.1 0
1.2 1.35 1
1.55 1.681 2

And then I tried to use the round() function

mutate(Result=round(Result, digits=Decimal))

but it's not working. All results are rounded off with 1 decimal point. Any advice will be greatly appreciated!

Upvotes: 1

Views: 565

Answers (2)

Anoushiravan R
Anoushiravan R

Reputation: 21908

Another option which is a mixture of tidyverse and base R:

library(dplyr)

df %>%
  rowwise() %>%
  mutate(Result = case_when(
    grepl("\\.", Limit) ~ round(Result, nchar(unlist(strsplit(as.character(Limit), "\\."))[2])),
    TRUE ~ Limit
  ))

# A tibble: 3 x 3
# Rowwise: 
  Limit Result Decimal
  <dbl>  <dbl>   <int>
1  1      1          0
2  1.2    1.4        1
3  1.55   1.68       2

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101257

You can try the code below

transform(
    df,
    Result2 = round(Result, (Limit %% 1 != 0) * nchar(gsub(".*\\.", "", Limit)))
)

which gives

  Limit Result Result2
1  1.00  1.100    1.00
2  1.20  1.350    1.40
3  1.55  1.681    1.68

Upvotes: 1

Related Questions