0

I would like to replace numeric values with strings. numeric range is between -1 and 1 my dput of a df is below.

   structure(list(m = c(-0.226, 0.11, 0.143, -0.095, -0.007, -0.232, 
-0.258, -0.438, -0.199, -0.419, -0.41, -0.271, -0.176, -0.33, 
-0.335, -0.59, -0.724, -0.161, -0.237, -0.223, -0.041, -0.627, 
-0.37, 0.055, -0.215, -0.287, -0.378, 0.006, -0.381, -0.598, 
-0.179, -0.259, 0.147, -0.08, 0.172, 0.035, -0.458, -0.254, -0.373, 
-0.319)), .Names = "m", row.names = c(NA, -40L), class = "data.frame")

When i run the below code it does not give the intended outcome.

m[m >= 0.3] <- "a"
m[(m < 0.3 & m >= 0.2)] <- "b"
m[(m < 0.2 & m >= 0.1)] <- "c"
m[(m < 0.1 & m >= 0.05)] <- "d"
m[(m < 0.05 & m >= 0)] <- "e"
m[(m < 0 & m >= -0.05)] <- "f"
m[(m < -0.05 & m >= -0.1)] <- "g"
m[(m < -0.1 & m >= -0.2)] <- "h"
m[(m < -0.2 & m >= -0.3)] <- "i"
m[m < -0.3] <- "j"

I also tried with adding a "," at the end like the below :

m[m < -0.3,] <- "j"

I believe the code is quite self-explanatory : i would like to change the values in a range by a character string. The inequality with negative values does not seem to work...

Thanks.

Chrisftw
  • 119
  • 1
  • 8

1 Answers1

1

This is your problem:

> -1 < -2
[1] FALSE
> "-1" < "-2"
[1] TRUE

Since you are replacing numbers with strings within the same variable, the numbers will be coerced to strings. Therefore inequalities with negative numbers will return wrong results.

What I would recommend is to use a second variable m2 to store the changes and keep mintact.

m2 = m

m2[m >= 0.3] <- "a"
m2[(m < 0.3 & m >= 0.2)] <- "b"
m2[(m < 0.2 & m >= 0.1)] <- "c"
m2[(m < 0.1 & m >= 0.05)] <- "d"
m2[(m < 0.05 & m >= 0)] <- "e"
m2[(m < 0 & m >= -0.05)] <- "f"
m2[(m < -0.05 & m >= -0.1)] <- "g"
m2[(m < -0.1 & m >= -0.2)] <- "h"
m2[(m < -0.2 & m >= -0.3)] <- "i"
m2[m < -0.3] <- "j"

Result:

> m2
   m
1  i
2  c
3  c
4  g
5  f
6  i
7  i
8  j
9  h
10 j
11 j
12 i
13 h
14 j
15 j
16 j
17 j
18 h
19 i
20 i
21 f
22 j
23 j
24 d
25 i
26 i
27 j
28 e
29 j
30 j
31 h
32 i
33 c
34 g
35 c
36 e
37 j
38 i
39 j
40 j
R. Schifini
  • 9,085
  • 2
  • 26
  • 32