Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove % sign from end of number in dataframe in R

I was wondering how to find elements that end in % and remove the % sign from those elements?

data <- read.table(text="
COURSE          CLASE  GROUP_A   GROUP_B
algebra         1         25%        8%
algebra         2         35%        9%
number_theory   3         18%        7%
number_theory   4         14%        11%
math_games      5         12%        5%
math_games      6         19%        4%
",h=TRUE)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

lapply over the columns removing any % at the end and then convert the types in the data frame to numeric if they should be numeric. No packaes are used.

data |>
  replace(TRUE, lapply(data, sub, pattern = "%$", replacement = "")) |>
  type.convert(as.is = TRUE)

giving:

         COURSE CLASE GROUP_A GROUP_B
1       algebra     1      25       8
2       algebra     2      35       9
3 number_theory     3      18       7
4 number_theory     4      14      11
5    math_games     5      12       5
6    math_games     6      19       4

With dplyr it is similar but we use across:

library(dplyr)

data %>%
  mutate(across(everything(), ~ sub("%$", "", .x))) %>%
  type.convert(as.is = TRUE)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading