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 :
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)