1

I have a large number of patient data that I'd like to use to produce health reports for. I'd like to produce one file for each patient with the file name being the subject ID.

The data looks like this:

library(tidyverse)
library(reshape2)

set.seed(3344)
subject_id <- as.factor(1:10)
var1 <- rnorm(n = length(subject_id), mean = 100, sd = 12)
var2 <- rnorm(n = length(subject_id), mean = 50, sd = 10)
var3 <- rnorm(n = length(subject_id), mean = 200, sd = 100)
df <- data.frame(subject_id, var1, var2, var3)

df <- df %>%
    melt(., id.vars = "subject_id", measure.vars = c(2:4))

I've done this once before, producing a pdf file that had one subject per page, however with our new system we need the files in .jpg format, one file per subject, and each file named the subject ID. When doing this to the large PDF file I did it like this:

plot <- ggplot(df, aes(x = variable, y = value, fill = variable)) +
    geom_bar(stat = "identity", position = position_dodge(width = 0.8)) +
    facet_wrap(~subject_id)

library(plyr)

pdf("Plot Example.pdf")
dlply(df, .(subject_id), function(x) plot %+% x)
dev.off()

However, I'm stuck as to how to produce each subject as a single file, with their ID as the file name, and the file type to be a .jpg. Any help would be greatly appreciated.

2
  • Rather than pdf/dev.off try using ggsave(). Include it to the function you are passing to dlply. Or you could also move the pdf/dev.off inside that function as well. Commented Jan 20, 2020 at 21:12
  • Thanks, I've tried to add the ggsave() function to the dlply call I'm making, however no matter where I add it I get an error: dlply(df, .(subject_id), function(ggsave(x)) plot %+% x). Within ggsave() I know I can specify that I want a .jepg however this wouldn't solve the issue of printing one file per subject with each file name being the subject ID. Or would it? Thanks! Commented Jan 20, 2020 at 21:23

1 Answer 1

1

Not very familiar with dlply, but you can try the following:

library(purrr)
library(ggplot2)

plotdf <- function(i){
    g = ggplot(i, aes(x = variable, y = value, fill = variable)) +
    geom_bar(stat = "identity", position = position_dodge(width = 0.8)) 
    ggsave(g,file=paste0(unique(i$subject_id),".png"))
}

df %>% split(.$subject_id) %>% map(plotdf)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.