【发布时间】:2019-05-27 14:18:49
【问题描述】:
我有一个数据框,每个人一行。这些列是一个结果变量,然后是该结果的一堆潜在预测变量。作为我的数据分析的初步步骤,我想使用 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>
我的实际数据集有超过 20 个预测变量,所以我想要一种生成 20 多个 ggplots 的好方法,并且理想情况下将其保持在这样的管道格式中,这样我可以在绘图工作后添加额外的步骤。
【问题讨论】:
-
当遍历您的预测向量时,
class(.)将始终是字符。你的意思是指你的df的那一列吗?即class(df[[.]])。其次,ifelse不能用于返回这种类型的对象afaik,最好使用标准if。