lundi 6 janvier 2020

Replace first number character with sub and if in R

I want to replace these 3 characters numbers that begin with 5 to 1. I tried to use a sub if conditional, but it failed

DO_concatenated:

    DTNASC   AGE
1   3031997  520
2   9022017  0
3   13071933 83
4   6022002  515
5   2061966  50
6   28121946 70
7   4121955  61
8   3101943  73
9   6022017  20
10  14012017 0
11  20071931 8

if((nchar(DO_concatenated$AGE) == 3)&(funcaoidade(DO_concatenated$AGE) == 5)){
  DO_concatenated$IDADE = sub(pattern = 5, replacement = 1, DO_concatenated$AGE) 
}

If it worked, the output would be something like that:

    DTNASC   AGE
1   3031997  120
2   9022017  0
3   13071933 83
4   6022002  115
5   2061966  50
6   28121946 70
7   4121955  61
8   3101943  73
9   6022017  20
10  14012017 0
11  20071931 8

I did that before to remove variables that begin with 4, with the following code:

if((nchar(DO_concatenated$IDADE) == 3)&(funcaoidade(DO_concatenated$IDADE) == 4)){
  DO_concatenated$IDADE = sub(pattern = 4, replacement = "", DO_concatenated$IDADE) 
}

and it worked!

"funcaoidade" looks for the first character of the number

funcaoidade = function(x){
  substr(x, start = 1, stop = 1)
}

so, whats the difference? thanks in advance!

Aucun commentaire:

Enregistrer un commentaire