Home > Net >  Error when using mutate_if or mutate(across()) to convert all columns from character to numeric
Error when using mutate_if or mutate(across()) to convert all columns from character to numeric

Time:12-30

For my learning objective, I would appreciate if someone could correct and explain why neither of these two solutions work

Let's say I have

str(b)
tibble [3 × 3] (S3: tbl_df/tbl/data.frame)
 $ Intensity.DISEASE5: chr [1:3] "27.37" ...
 $ Intensity.DISEASE6: chr [1:3] "27.47" ...
 $ Gene.names        : chr [1:3] "IGLL5;IGLC1"  ...

I want to convert all columns to numeric values as.numeric except for the character values in b$Gene.names.

I tried

b %>% mutate_if((str_detect(colnames(.), "Intensity") & is.character), as.numeric)

Error in str_detect(colnames(.), "Intensity") & is.character :
operations are possible only for numeric, logical or complex types

And

b %>% mutate(across(where(contains("Intensity")), as.character))

Error in mutate(): ! Problem while computing ..1 = across(where(contains("Intensity")), as.character). Caused by error in across(): ! Can't convert fn, an integer vector, to a function.

Data

b <- structure(list(Intensity.DISEASE5 = c("27.3736820220947", "23.7670879364014", 
"24.8043975830078"), Intensity.DISEASE6 = c("27.4711933135986", 
"26.1416263580322", "25.3245735168457"), Gene.names = c("IGLL5;IGLC1", 
"QSOX1", "GFRA2")), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

CodePudding user response:

you do not need the dplyr::where() function when using dplyr::contains()... though as @DarranTsai pointed out in the comment, you might want to use it in combination to restrict the selection further (not only part of the column name but also data type):

library(dplyr)

b %>% dplyr::mutate(dplyr::across(dplyr::contains("Intensity"), as.character)) 
# you could use as.numeric or even readr::parse_number instead of as.character to convert to a numeric data type

about the dplyr::mutate_if() you should not worry, since acording to the documentation "[...] Scoped verbs (⁠_if⁠, ⁠_at⁠, ⁠_all⁠) have been superseded by the use of across() in an existing verb [...]"

  • Related