Search code examples
rdplyrlapplymagrittr

Magritttr + lapply where first argument isn't to LHS


I'd like to pass a data frame into lapply via %>%, but I need to be able to access the names of the columns, so my lapply arguments are something like this:

mydf %>%
   lapply( 1:length(.), function(x) {
        manipulate_df( mydf[x], using_column_names(names(mydf)[x] )
   })

However, when I try that, I get the following error:

Error in match.fun(FUN) :
   '1:length(.)' is not a function, character or symbol

As far as I can tell R and lapply don't like 1:length(.). I suppose a valid option is breaking the chain, but I'd like to learn how to do it properly.


Solution

  • Your issue here is that %>% is inserting mydf as the first argument (so that three arguments are getting passed to lapply. Try wrapping the entire lapply expression in brackets. This prevents the insertion behavior:

    mydf %>%
       { lapply( 1:length(.), function(x) {
            manipulate_df( mydf[x], using_column_names(names(mydf)[x] )
       }) }
    

    I think the prettiest fix would be to make a new function:

    manipulate_whole_df = function(mydf)
      lapply( 1:length(mydf), function(x)
                manipulate_df( mydf[x], using_column_names(names(mydf)[x] ) ) )
    
    mydf %>%
      manipulate_whole_df
    

    Or even

    library(tidyr)
    
    mydf %>%
      gather(variable, value) %>%
      group_by(variable) %>%
      do(manipulate_df(.$value, 
                       .$variable %>% first %>% using_column_name ) )