Search code examples
rmagrittr

is it possible to pipe a data frame variable


I have two separate operations:

allusers$ref <- str_to_upper(allusers$ref)

allusers$ref <- str_trim(allusers$ref)

Is it possible to pipe them?

allusers$ref <- str_to_upper(allusers$ref) %>% str_trim(allusers$ref)

gives

"Error in match.arg(side) : 'arg' must be of length 1"

and ideally I wouldn't be typing allusers$.. each time


Solution

  • Sure, you may write

    allusers$ref <- allusers$ref %>% str_to_upper %>% str_trim
    

    That's because you want to apply str_to_upper and str_trim to a string, and by piping allusers$ref you indeed pass as the first argument this string.

    A somewhat traditional way would be

    allusers <- allusers %>% mutate(ref = str_trim(str_to_upper(ref)))