Home > Software design >  Use lme() within the dplyr pipe
Use lme() within the dplyr pipe

Time:03-02

Question

Hello, I would like to use the function lme() from the nlme package inside the pipe.

Data

library(tidyverse)
library(nlme)

df <- tribble( 
  ~id_pat,  ~diff,
  1,          -15, 
  2,         NA,
  3,         -25.2,
  4,          46.2,
  1,         16.4,
  2,         -12,
  3,         9, 
  4,         14
)

Code

This works:

lme(diff ~ 1, random = ~1 |
      id_pat, na.action = na.omit, data = df)

This doesn't work:

df %>%
   lme(diff ~ 1, random = ~1 |
       id_pat, na.action = na.omit)

I've tried several solutions, none of them work:

# With pull
df %>%
  lme(pull(.x["diff"]) ~1, random = ~1 |
      pull(.x["id_pat"]), na.action = na.omit))

# With eval & subtitue
b <- df["id_pat"]
df %>%
  lme(eval(substitute(j ~ 1, list(j = as.name("diff")))), random = ~1 |
      b, na.action = na.omit, data = df_time_point_as_col_pf)

# With paste0
b <- df["id_pat"]
df_time_point_as_col %>% 
  lme(paste0(diff_avt_dd_pdt_dv, "~1"), random = ~1 |
      b, na.action = na.omit
      )

# With broom
library(broom)
df %>%
  broom::tidy(lme(pull(.x["diff"]) ~1, random = ~1 |
                  pull(.x["id_pat"]), na.action = na.omit))

# With broom.mixed
library(broom.mixed)
df %>%
  broom.mixed::tidy(lme(pull(.x["diff"]) ~1, random = ~1 |
                        pull(.x["id_pat"]), na.action = na.omit))

Thank you very much in advance

CodePudding user response:

Refer the data with .

library(dplyr)
library(nlme)

df %>% 
  lme(diff ~ 1, random = ~1 |
        id_pat, na.action = na.omit, data = .)

#Linear mixed-effects model fit by REML
#  Data: . 
#  Log-restricted-likelihood: -28.5764
#  Fixed: diff ~ 1 
#(Intercept) 
#   4.398488 

#Random effects:
# Formula: ~1 | id_pat
#        (Intercept) Residual
#StdDev:    9.773561 22.46122

#Number of Observations: 7
#Number of Groups: 4 

CodePudding user response:

Using . for the data as @RonakShah suggests is fine. You can also name the arguments provided to make sure that data is the first unspecified argument in the argument list

df %>% lme(fixed = diff ~ 1, random = ~1|id_pat, na.action = na.omit)

i.e. since args(lme) is

function (fixed, data = sys.frame(sys.parent()), random, correlation = NULL, 
    weights = NULL, subset, method = c("REML", "ML"), na.action = na.fail, 
    control = list(), contrasts = NULL, keep.data = TRUE) 

and we have explicitly specified fixed, the piped argument will be identified as data.

  • Related