Вот способ, которым вы можете сделать это с помощью пакета stringr;
library(dplyr)
library(stringr)
data <-
data.frame(
DTNASC = c(3031997, 9022017, 13071933, 6022002, 2061966, 28121946, 4121955,
3101943, 6022017, 14012017, 20071931),
AGE = c(520, 0, 83, 515, 50, 70, 61, 73, 20, 0, 8)
)
data %>%
mutate(# Replacement of Age
# To convert it into character to make it easier
AGE = as.character(AGE),
# Here 5 is the character we are checking in first character
# str_sub(AGE, 1, 1) -> Checks first character
# nchar(AGE) == 3 -> Checks if the length of AGE is 3
# str_replace(AGE, "5", "1") -> Replaces 5 with 1
# as.numeric() -> To convert to a number
AGE = ifelse(str_sub(AGE, 1, 1) == "5" & nchar(AGE) == 3,
as.numeric(str_replace(AGE, "5", "1")),as.numeric(AGE)),
# Replacement of DTNASC
# To convert it into character to make it easier
DTNASC = as.character(DTNASC),
# Here 4 is the character we are checking in first character
# str_sub(DTNASC, 1, 1) -> Checks first character
# nchar(DTNASC) == 7 -> Checks if the length of DTNASC is 7
# str_replace(DTNASC, "4", "") -> Replaces 4 with null
# as.numeric() -> To convert to a number
DTNASC = ifelse(str_sub(DTNASC, 1, 1) == "4" & nchar(DTNASC) == 7,
as.numeric(str_replace(DTNASC, "4", "")),as.numeric(DTNASC)))
# DTNASC AGE
# 3031997 120
# 9022017 0
# 13071933 83
# 6022002 115
# 2061966 50
# 28121946 70
# 121955 61
# 3101943 73
# 6022017 20
# 14012017 0
# 20071931 8