Home > Mobile >  how to write R function to make values close to zero to zero and leaving others as is
how to write R function to make values close to zero to zero and leaving others as is

Time:01-25

I have a data frame with 3 columns and 40 rows. The 1st two columns contain a value range from -1 to 1, and the 3rd column contains the sum of the two columns. Therefore, I would like to change values closer to zero, such as 0.3, 0.2, 0.1, -0.1, -0.2, -0.3 in the 3rd columns to zero and the rest as it was.

library(dplyr)
set.seed(2)
D = data.frame(from = runif(40, -1,1), to = runif(40,-1,1)) %>% dplyr::mutate(weight = from   to)

I appreciate your help.

CodePudding user response:

With replace, check if the absolute value is below a threshold:

thrs = 0.5
transform(D, weight = replace(weight, abs(weight) < thrs, 0))

Or in the dplyr framework:

D %>% 
  mutate(weight = replace(weight, abs(weight) < 0.5, 0))
  •  Tags:  
  • r
  • Related