Автоматизация поисковых графиков с использованием purrr и нескольких разных наборов данных

#r #ggplot2 #tidyverse #purrr

#r #ggplot2 #tidyverse #purrr

Вопрос:

Мне очень нравится использовать purrr для автоматизации моих исследовательских графиков, о чем я узнал из этого сообщения в блоге: https://www.r-bloggers.com/2018/08/automating-exploratory-plots-with-ggplot2-and-purrr /

Однако одна из проблем с кодом в этом сообщении в блоге заключается в том, что вы должны указать набор данных в функции. Я хотел бы обобщить набор данных в функции, чтобы я мог изменять набор данных по своему усмотрению.

Я перепробовал все, что мог придумать, чтобы сделать это, но я действительно застрял. Есть предложения?

 ###Sample dataset

dataSet <- data.frame(id = c(1,1,2,2),
                      col1 = c(3.5,4.5,6.5,7.6),
                      col2 = c(1.2,2.3,4.5,6.7),
                      col3 = c(9.8,7.6,5.4,5.6),
                      timepoint = c(1,2,1,2))

###Sample function

plot_func <- function(x,y,d) {
  ggplot(d, aes(x = .data[[x]], y = .data[[y]]))  
    geom_line(aes(x = .data[[x]], y = .data[[y]], group = id), size = 1, alpha = 0.3)
}

###Specify variables of interest

exposures <- names(dataSet)[2:4]
timepoint <- names(dataSet)[5]

##Name variables of interest

exposures <- purrr::set_names(exposures)
timepoint <- purrr::set_names(timepoint)

###This doesn't work because need to specify the dataset, but no matter what I try I can't figure out where to put the dataset in the formula

plots = map(exposures,
            ~map(timepoint, plot_func, y = .x) )
 

Ответ №1:

Если вы выполняете цикл только exposures с одной временной точкой, то это должно быть сделано следующим образом:

 plots = map(exposures, ~ plot_func(x = timepoint, y = .x, d = dataSet))
 

Вы можете просто использовать нотацию lamda для заполнения переменных, которые вы хотите указать. .x ваш вклад map в этом случае exposures .

Смотрите код ниже:

 library(ggplot2)
library(purrr)

###Sample dataset

dataSet <- data.frame(id = c(1,1,2,2),
                      col1 = c(3.5,4.5,6.5,7.6),
                      col2 = c(1.2,2.3,4.5,6.7),
                      col3 = c(9.8,7.6,5.4,5.6),
                      timepoint = c(1,2,1,2),
                      timepoint2 = c(3,4,3,4))

### Sample function
plot_func <- function(x,y,d) {
  ggplot(d, aes(x = .data[[x]], y = .data[[y]]))  
    geom_line(aes(x = .data[[x]], y = .data[[y]], group = id), size = 1, alpha = 0.3)
}

### Specify variables of interest
exposures <- names(dataSet)[2:4]
timepoint <- names(dataSet)[5]
timepoint2 <- names(dataSet)[5:6]

##Name variables of interest
exposures <- purrr::set_names(exposures)
timepoint <- purrr::set_names(timepoint)
timepoint2 <- purrr::set_names(timepoint2)

### This works

plots <- map(exposures, ~ plot_func(x = timepoint, y = .x, d = dataSet))

plots
#> $col1
#> $col2
#> $col3
 

Если вы хотите перебирать exposures переменные и временные точки (я добавил timepoint2 в качестве другого столбца временных точек), вы можете использовать вложенный map вызов:

 plots2 <- map(exposures, ~ map(timepoint2, function(z) plot_func(x = z, y = .x, d = dataSet)))

plots2
#> $col1
#> $col1$timepoint
#> $col1$timepoint2
#> $col2
#> $col2$timepoint
#> $col2$timepoint2
#> $col3
#> $col3$timepoint
#> $col3$timepoint2
 

Создано 2021-01-14 пакетом reprex (версия 0.3.0)

Комментарии:

1. Большое вам спасибо!!