Reputation: 175
I have a very simple issue I don't know how to solve.
I have the following list of very small values before conversion:
[,1]
V8530 0.00000009686643
V6196 0.00297853602192
V714 0.99999999760977
V9461 0.00003742696819
V9518 0.00141335323766
V9511 0.00047082401517
V9651 0.00011655255640
V6358 0.00000056338519
V5930 0.00000155667916
If the value > 0.09 then I want to convert it to 0. If the value is less than 0.09 I want to substitute the value for 1.
Logic for conversion
predicted_train_0_1[predicted_train_0_1 < 0.09] <- 1
predicted_train_0_1[predicted_train_0_1 > 0.09] <- 0
These are my values after the conversion:
[,1]
V8530 0
V6196 0
V714 0
V9461 0
V9518 0
V9511 0
V9651 0
V6358 0
V5930 0
I might be in need of sleeping or something else, but I can't figure out why!? The logic seems too simple to be wrong IMHO.
Any help is more than welcome.
Thanks!
Upvotes: 1
Views: 121
Reputation:
Your first logic predicted_train_0_1[predicted_train_0_1 < 0.09] <- 1
returned a vector of 1 and values which are > 0.09. Therefore, the second logic would return a list of all 0.
My solution is using the dplyr
library:
library("dplyr")
x <- x %>% mutate(
predicted_train = if_else(val > 0.9, 0, 1)
)
Here is the x
:
x <- data.frame(val=c(0.00000009686643,
0.00297853602192,
0.99999999760977,
0.00003742696819,
0.00141335323766,
0.00047082401517,
0.00011655255640))
Upvotes: 0
Reputation: 7630
This is a common source of bugs. When you use a logical test on an object that you mutate, you have to remember that the result of your test will change. There are a variety of solutions here, but the general idea is to store the result of the test in another object, before the input to the test is mutated.
The most basic solution:
index <- x < 0.09
x[index] <- 1
x[! index] <- 0
x
# [1] 1 1 0 1 1 1 1 1 1
ifelse
does this behind the scenes, just with more error checking.
As @thelatemail points out, since you happen to be converting TRUE
values in index
to 1
, and FALSE
values to 0
, in this case, you may be better served by just using index
.
Data:
x <- c(0.00000009686643,
0.00297853602192,
0.99999999760977,
0.00003742696819,
0.00141335323766,
0.00047082401517,
0.00011655255640,
0.00000056338519,
0.00000155667916)
Upvotes: 3