0

I followed the dplyr-solution here: converting multiple columns from character to numeric format in r to convert multiple character columns to numeric.

The code

is_all_numeric <- function(x) 
{
  !any(is.na(suppressWarnings(as.numeric(na.omit(x))))) & is.character(x)
}
df %>%
   mutate_if(is_all_numeric,as.numeric) #%>%
   str()

works perfectly. However, if I try to assign it to the df(i.e. make changes to column type permanent) using

df <- df %>%
   mutate_if(is_all_numeric,as.numeric) #%>%
   str()

df becomes Null. Hence, I am wondering what's going on and how to make the numeric formats permantenly using these lines of code?

MRE

df <- tribble(~date, ~value,
        "2017-01-01", 1,
        "2017-01-02", 2,
        "2017-01-02", 3,
        "2017-01-03", 4,
        "2017-01-03", NA,
        "2017-01-04", 6,
        "2017-01-09", 9) %>% 
  arrange(date) %>% 
  mutate(to_date=cumsum(value))
Magasinus
  • 83
  • 11

2 Answers2

5

Use this instead -- across did not exist 7 years ago when the link in the question was written:

df %>% mutate(across(.fns = type.convert))

or with only base R:

replace(df, TRUE, lapply(df, type.convert))
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
2

Follow akruns answer, this is just adding to explain what your problem is.

Note that

df <- str(df)
df
NULL

So the error you're experiencing is that you copied a solution without understanding each part of it.

A good tip for looking up solutions is to

  1. Test and see that it works
  2. Use "help" to see what each part does (preferably every part).
  3. Try and see if you can make another small example indicating you understand how it works

In our case you could use help("mutate_if") and immediately it states that [lifecycle: Superseded], indicating that a new and better implementation exists (akruns answer), and reading through you notice nothing suspicious (no NULL return), so the next part is help("str") or help("%>%"). And in the first of those you'll see under return that

str does not return anything, for efficiency reasons. The obvious side effect is output to the terminal.

indicating the problem is with this function.

Oliver
  • 8,169
  • 3
  • 15
  • 37
  • 1
    Thank you, I indeed underestimated the effect of `str`. `df<- df%>%mutate_if(is_all_numeric,as.numeric)` works as a (superseded) alternative. The difference is that this code keeps string columns as character, while G.Grothendiek's suggestion using `across` converts them to factors. – Magasinus Mar 28 '21 at 20:13