I wrote down a function to remove/ replace % sign in R. The code is executing but the variable is unchanged

rep_spl_chr <- function(df,variable1){
df%>%
mutate(variable1=gsub("%","",variable1))
return(df)
}

Trying it:

loan2<-rep_spl_chr(loan2,Debt.To.Income.Ratio)
>  Debt.To.Income.Ratio
[1] "14.90%" "28.36%" "23.81%" "14.30%" "18.78%" "20.05%" "26.09%"

but it still dont replace the %

2 Answers

1
igoR87 On

Your code did not select the desired column. you can do so with df[ , "nameofvariable"]. Thus I would use instead:

# the function would be
rep_spl_chr <- function(df,variable1){
  return(gsub("%","", df[ , variable1], fixed= TRUE))
}

# some reproducible data (please provide it in future)
loan2 <- data.frame(Debt.To.Income.Ratio= c("14.90%", "28.36%", "23.81%", "14.30%", "18.78%", "20.05%", "26.09%"))

# saving what the function does
loan2$Debt.To.Income.Ratio_new <- rep_spl_chr(loan2,"Debt.To.Income.Ratio")

# having a look at the results
  Debt.To.Income.Ratio Debt.To.Income.Ratio_new
1               14.90%                    14.90
2               28.36%                    28.36
3               23.81%                    23.81
4               14.30%                    14.30
5               18.78%                    18.78
6               20.05%                    20.05
7               26.09%                    26.09
0
Gregor Didenko On

How about doing it the old fashioned way, no need for tidyverse here.:

rep_spl_chr <- function(df, variable){
    df[, variable] <- gsub("%", "", df[, variable])
    return(df)
}