0

I get error below when I want to apply a function on the labelled columns. here as an example I applied mean() function.

library(tidyr)
library(dplyr)
library(Hmisc)   
df <- data.frame(a = LETTERS[1:5],
                     b = c(1,2,NA,4,5))
    Hmisc::label(df$a) <- "hi hi"
    Hmisc::label(df$b) <- "bye bye"
    
    names(df) <- Hmisc::label(df)
    df %>%
        mutate(`hi hi` = paste0(`hi hi`, "people"),
               `bye bye` = replace_na(`bye bye`, mean(`bye bye`, na.rm = T))) 
    
    #mean(df$`bye bye`, na.rm = T)

The error is:

Error in `mutate()`:
ℹ In argument: `bye bye = replace_na(`bye bye`, mean(`bye bye`, na.rm = T))`.
Caused by error in `vec_assign()`:
! Can't convert `replace` <double> to match type of `data` <labelled>.
Backtrace:
  1. df %>% ...
 10. tidyr:::replace_na.default(`bye bye`, mean(`bye bye`, na.rm = T))
 11. vctrs::vec_assign(data, missing, replace, x_arg = "data", value_arg = "replace")
Error in mutate(., `hi hi` = paste0(`hi hi`, "people"), `bye bye` = replace_na(`bye bye`, :

Caused by error in `vec_assign()`:
! Can't convert `replace` <double> to match type of `data` <labelled>.
Mathica
  • 1,241
  • 1
  • 5
  • 17

1 Answers1

1

The type seems to conflict with replace_na; here bye bye probably need to be numeric:

library(dplyr)

df |>
  mutate(`hi hi` = paste0(`hi hi`, "people"),
         `bye bye` = as.numeric(`bye bye`),
         `bye bye` = replace_na(`bye bye`, mean(`bye bye`, na.rm = T)))

However you might also consider going the base way:

is.na(df$`bye bye`) <- mean(df$`bye bye`, na.rm = TRUE)

Output:

    hi hi bye bye
1 Apeople       1
2 Bpeople       2
3 Cpeople       3
4 Dpeople       4
5 Epeople       5
harre
  • 7,081
  • 2
  • 16
  • 28