Replace All Values Lower Than Threshold in R

Replace all values lower than threshold in R

pmax is a good candidate for this

  > pmax(x, 1)
[1] 1 1 1 2 3

R: replace all values in a dataframe lower than a threshold with NA

Try this:

 df[df<minval]=NA

df < minval creates a boolean matrix, which is used to select the values you want to replace with NA.

Replacing values bigger than threshold with 0 in specified range of columns in R dataframe

Dplyr (use the latest version) has a nice "across()" function to be used with mutate. Just be sure to update your dplyr package as it is quite recent

library(dplyr)

df1 %>% mutate(across(where(is.numeric), function(x) ifelse(x >= 10, 0, x)))

ID string1 S_2018_p S_2019_p S_2020_p S_2021_p string2
1: a1 x2 3 3 0 4 si
2: a2 g3 5 5 4 0 q2
3: a3 n2 0 6 0 3 oq
4: a4 m3 3 0 9 8 mx
5: a5 2w 9 1 0 5 ix
6: a6 ps2 0 4 7 4 p2
7: a7 kg2 6 0 9 6 2q

Replace columns less than a threshold to 0

dplyr:

df <- mutate_all(df, funs(ifelse(. < 0.5, 0, .)))

base R:

df[df < 0.05] <- 0

Use dplyr to change all values above threshold to NA

We can assign the output to the original object to make those changes as the %>% will not do the output printed on the console.

df <- df %>% 
mutate(across(everything(), ~ ifelse(. > 8, NA, .)))

Or another option is %<>% operator from magrittr

library(magrittr)
df %<>%
mutate(across(everything(), ~ ifelse(. > 8, NA, .)))

Replace values outside of max/min values with max/min values

It can be done with pmin/pmax

a[, colD := pmin(pmax(the_min, colB), the_max)]
a
# colA colB colD
# 1: A 1 3
# 2: B 2 3
# 3: C 3 3
# 4: D 4 4
# 5: E 5 5
# 6: F 6 6
# 7: G 7 7
# 8: H 8 7
# 9: I 9 7
#10: J 10 7

How to replace row values based on a threshold of a sparse matrix in R?

I modified @Bas solution so that it utilizes the sparsity of the matrix allowing to increase the performance.

mat@x[mat@x > thres_array[mat@i + 1] ] <- 1

mat@x gives the non-zero elements of the sparse matrix and mat@i gives what row that non-zero element belongs to (you have to add 1 since it is zero-indexed). Since the elements of thres_array are based on the corresponding row you can make a logical vector from mat@x > thres_array[mat@i + 1] and reassigns those values to 1.

Replace all values in a matrix 0.1 with 0

ifelse should work:

mat <- matrix(runif(100),ncol=5)
mat <- ifelse(mat<0.1,NA,mat)

But I would choose Harlan's answer over mine.

mat[mat < 0.1] <- NA


Related Topics



Leave a reply



Submit