Home > Software design >  Map function in Purr
Map function in Purr

Time:09-17

I am trying to create line plots for each PAT using map and ggplot. The following code doesnt work , i have also tried passing in a list

Lb1 <- labs[, c("PAT","RES","PARAMCD","AVISITN","LBSTNRHI")]
subj <- unique(lb1$PAT)
p1 <- map(.x = subj, .f = ~ lb1 %>%  
  filter(SUBJID == subj[.x] & PARAMCD %in% c("CA", "HGB", "BILI", "BILDIR")) %>% 
  ggplot(aes(VISIT,AVAL,color = PARAMCD))  
  geom_point()  
  geom_line()  
  ggtitle(label = subj[.x]))
p1

CodePudding user response:

It's always difficult to help if you don't share the data.

I can spot few error/inconsistencies in your code.

  1. First, you have unique values of PAT column in subj (subj <- unique(lb1$PAT)) but later in map you filter the SUBJID column with those values. Is that correct? Or should you have unique values of SUBJID in subj i.e subj <- unique(lb1$SUBJID).

  2. You are passing the values of subj in map so I don't think subj[.x] makes sense. .x already has the value that you want so you can use it directly.

Try -

library(purrr)
library(ggplot2)

p1 <- map(.x = subj, .f = ~ lb1 %>%  
            filter(SUBJID == .x & PARAMCD %in% c("CA", "HGB", "BILI", "BILDIR")) %>% 
            ggplot(aes(VISIT,AVAL,color = PARAMCD))  
            geom_point()  
            geom_line()  
            ggtitle(.x)
          )
p1
  • Related