Home > other >  Finding rows with decimal points and multiply them by 1000 - R
Finding rows with decimal points and multiply them by 1000 - R

Time:11-18

This is an example of the dataset

n | rbc
-------
1 | 2500
2 | 2.7
3 | 4500

I want to find rows that has decimal points and then multiply them by 1000

CodePudding user response:

Here is a way with grep. Search for the dot regex, escaped since it is a meta-character. And subset the data with its return value.

i <- grep('\\.', df1$rbc)
df1$rbc[i] <- df1$rbc[i] * 1000
df1
#>   n  rbc
#> 1 1 2500
#> 2 2 2700
#> 3 3 4500
#> 4 4    1
#> 5 5   18

Created on 2022-11-17 with reprex v2.0.2


To also multiply other small numbers by 1000 the following code should be used instead of the code above. dig is the number of digits of the numbers that are to be multiplied.

dig <- 2L

i <- grepl('\\.', df1$rbc)
j <- nchar(df1$rbc) <= dig
df1$rbc[i | j] <- df1$rbc[i | j] * 1000
df1
#>   n   rbc
#> 1 1  2500
#> 2 2  2700
#> 3 3  4500
#> 4 4  1000
#> 5 5 18000

Created on 2022-11-17 with reprex v2.0.2


Data

df1 <-'n | rbc
1 | 2500
2 | 2.7
3 | 4500
4 | 1.0
5 | 18.0'
df1 <- read.table(textConnection(df1), header = TRUE, sep = '|')
str(df1)
#> 'data.frame':    5 obs. of  2 variables:
#>  $ n  : num  1 2 3 4 5
#>  $ rbc: num  2500 2.7 4500 1 18

Created on 2022-11-17 with reprex v2.0.2

CodePudding user response:

Assuming all values in the rbc column are numeric and you only want to look for values between -1 and 1 in that column, then one trick would be to find rows where the integer part or rbc is zero and adjust only those values:

has_dec <- floor(abs(df$rbc)) == 0
df[has_dec, "rbc"] <- df[has_dec, "rbc"] * 1000

CodePudding user response:

If the data are numeric, use the modulo operator (%%).

within(df, rbc <- rbc*(1   ((rbc %% 1) > 0)*999))
#>   n  rbc
#> 1 1 2500
#> 2 2 2700
#> 3 3 4500
  •  Tags:  
  • r
  • Related