0

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!

Tuck
  • 3
  • 2
  • How are you calling the function? Note that values that change inside a function, aren't persisted outside the function. R functions are meant to return new values, not replace values in the calling environment. Are you saving the result of this function anywhere? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Feb 22 '23 at 14:59
  • Not sure what you mean by indirection. Tidyverse functions generally use tidyeval, so to pass bare column names to a function requires different syntax – camille Feb 22 '23 at 15:00
  • You can learn more about the tidyverse's non-standard evaluation (NSE) [here](https://dplyr.tidyverse.org/articles/programming.html) – Limey Feb 23 '23 at 08:56

0 Answers0