0

Using R, what ifelse, if_else, if, for, or other statements should be used on a data.frame to find the negative numbers and replace them with the positive number 0.001? Said another way, replace all negative numbers in the data.frame with the positive number 0.001. A base R, plyr or dplyr function would work.

set.seed(1)

dfTest <- data.frame(replicate(5, sample(c(-10:99), 7, rep = TRUE)))

In MS-Excel, the code might be =if(x<0, 0.001, x). There are several R examples for lists, just not many applicable for data.frames. Thanks.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Orknie
  • 97
  • 1
  • 8

2 Answers2

1

To achieve this you don't need to use ifelse(), this will do the job:

dfTest[dfTest < 0] <- 0.001
#result
  X1     X2 X3     X4 X5
1 19 62.000 74 13.000 85
2 30 59.000 44 61.000 27
3 53  0.001 68  3.000 43
4 89 12.000 99 19.000 55
5 12  9.000 31 32.000 44
6 88 65.000 75  0.001 10
7 93 32.000 92 32.000 81
fabla
  • 1,806
  • 1
  • 8
  • 20
1

It is simple. Just use this.

dftest[dftest < 0] <- 0.001

Neeraj
  • 1,166
  • 9
  • 21