У меня есть датафрейм с одной строкой на человека. Столбцы - это переменная результата, а затем группа потенциальных предикторов этого результата. В качестве предварительного шага моего анализа данных я хочу визуализировать каждую переменную предиктора и ее связь с результатом, используя ggplot. Мне нужна гистограмма для непрерывных переменных и гистограмма для категориальных.
Моя попытка
numeric <- c(0,1.1,2.4,3.1,4.0,5.9,4.2,3.3,2.2,1.1)
categorical <- as.factor(c("yes","no","no","yes","yes","no","no","yes","no","no"))
outcome <- as.factor(c("alive","dead","alive","dead","alive","dead","alive","dead","alive","dead"))
df <- data.frame(num = numeric, cat = categorical, outcome = outcome)
predictors <- c("num", "cat")
predictors %>%
walk(print(ggplot(df, aes(x=., fill=outcome)) +
{ifelse(class(.) == "factor", geom_bar(position="fill"), geom_histogram(position="fill", bins=10))}))
Но я получаю ошибку
Error in rep(no, length.out = length(ans)): attempt to replicate an object of type 'environment'
Traceback:
1. predictors %>% walk(print(ggplot(df, aes(x = ., fill = outcome)) +
. {
. ifelse(class(.) == "factor", geom_bar(position = "fill"),
. geom_histogram(position = "fill", bins = 10))
. }))
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. walk(., print(ggplot(df, aes(x = ., fill = outcome)) + {
. ifelse(class(.) == "factor", geom_bar(position = "fill"),
. geom_histogram(position = "fill", bins = 10))
. }))
10. map(.x, .f, ...)
11. as_mapper(.f, ...)
12. print(ggplot(df, aes(x = ., fill = outcome)) + {
. ifelse(class(.) == "factor", geom_bar(position = "fill"),
. geom_histogram(position = "fill", bins = 10))
. })
13. ifelse(class(.) == "factor", geom_bar(position = "fill"), geom_histogram(position = "fill",
. bins = 10)) # at line 9 of file <text>
Я ожидаю, что этот код два производит два графика
![categorical plot](https://i.stack.imgur.com/Z7Wit.png)
В моем фактическом наборе данных> 20 предикторов, поэтому я хотел бы получить хороший способ создать более 20 ggplots и в идеале сохранить его в таком конвейерном формате, чтобы я мог добавить дополнительные шаги после того, как я получу графики.