To get numeric values of character with division symbol /, an alternative way is to split the character so that the numbers without / are extracted. After that, the extracted numbers are converted to numeric, and then division of the numbers is conducted by using /.
# Define the function
getNumber <- function(string_vect){
extracted_number <- gsub(".*?([0-9/0-9]+).*","\\1", string_vect)
split_number <- strsplit(extracted_number, "/") |> unlist() |> as.numeric()
divided_number <- split_number[1]/split_number[2]
return(divided_number)
}
#Apply the function to the column
mydf <- data.frame(price = c("SR 50/4 pack", "SR 10/4"))
lapply(mydf$price, getNumber) |> unlist()
#[1] 12.5 2.5
If the column contains mixed characters, some of them with /, and others without it, the function can be modified with conditionals if and else as follows:
getAllnumber <- function(string_vect){
extracted_number <- gsub(".*?([0-9/0-9]+).*","\\1", string_vect)
if(grepl("/", string_vect)){
split_number <- strsplit(extracted_number, "/") |> unlist() |> as.numeric()
resulted_number <- split_number[1]/split_number[2]
}
else{
resulted_number <- extracted_number |> as.numeric()
}
return(resulted_number)
}
#apply the function to the column
mydf <- data.frame(price = c("SR 2356","SR 785","SR 50/4 pack",
"SR 10/4 pack","SR 490"))
lapply(mydf$price, getAllnumber) |> unlist()
#[1] 2356.0 785.0 12.5 2.5 490.0
# or
vapply(mydf$price, getAllnumber, numeric(1))
# SR 2356 SR 785 SR 50/4 pack SR 10/4 pack SR 490
# 2356.0 785.0 12.5 2.5 490.0
Edit to show the same function with no pipe
An exactly same function as can be defined without using any |> pipe as follows.
getAllnumber2 <- function(string_vect){
extracted_number <- gsub(".*?([0-9/0-9]+).*","\\1", string_vect)
if(grepl("/", string_vect)){
split_number <- as.numeric(unlist(strsplit(extracted_number, "/")))
resulted_number <- split_number[1]/split_number[2]
}
else{
resulted_number <- as.numeric(extracted_number)
}
return(resulted_number)
}
mydf <- data.frame(price = c("SR 2356","SR 785","SR 50/4 pack",
"SR 10/4 pack","SR 490"))
unlist(lapply(mydf$price, getAllnumber2))
This code will return the same result as the function with pipe:
#[1] 2356.0 785.0 12.5 2.5 490.0