I am trying to take a column and remove all non-numeric characters from its entries, turning it from chr to numeric. Input data example:
species <- c('Carabus dufouri', 'Opuntia ficus-indica', 'Lycaena phlaeas')
number <- ('3 adults', '4 and a half stands', '8 caterpillars')
data <- tibble (species, number)
data
# A tibble: 3 x 2
species number
<chr> <chr>
1 Carabus dufouri 3 adults
2 Opuntia ficus-indica 4 and a half stands
3 Lycaena phlaeas 8 caterpillars
My desired output would be:
number_f <- c(3, 4, 8)
data_f <- tibble (species, number_f)
data_f
species number_f
<chr> <dbl>
1 Carabus dufouri 3
2 Opuntia ficus-indica 4
3 Lycaena phlaeas 8
This code worked for me before wrapping into a function:
num_fix <- function(data, spalte) {
satz <- as.double(gsub("([0-9]+).*$", "\\1", data[[spalte]]))
data %>% mutate(spalte = satz)
}
But now the mutate doesn't seem to do anything. It must have something to do with indirection, but I'm having a hard time wrapping my head around it. Thank you!