r - 使用 R 绘制箱线图的选择方法出错
问题描述
我正在使用 ggplot 来显示带有多个变量的箱线图,并且我使用了 select 方法并且出现了这个错误,所以如何解决这个问题
library(dplyr)
p <- df
select(heart[,1],
trestbps,
chol,
thalach,
oldpeak,
ca,
target)
gather(key = "key",
value = "value",
-target)
ggplot(aes(y = value)) +
geom_boxplot(aes(fill = target),
alpha = .6,
fatten = .7) +
labs(x = "",
y = "",
title = "Boxplots for Numeric Variables") +
scale_fill_manual(
values = c("#fde725ff", "#20a486ff"),
name = "Heart\nDisease",
labels = c("No HD", "Yes HD")) +
theme(
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
facet_wrap(~ key,
scales = "free",
ncol = 2)
plot(p)
Error in UseMethod("select_") : no applicable method for 'select_' applied to an object of class "c('integer', 'numeric')"
解决方案
根据代码,这heart[,1]
意味着我们正在对第一列进行子集化,如果它是 a data.frame
,它将被强制转换为向量,因为drop = TRUE
默认情况下select
不能应用于向量。如果df
是数据集对象并且heart
是列之一,那么我们需要%>%
将两者连接起来。同样,需要连接到gather
library(dplyr)
p <- df %>%
select(heart, trestbps,
chol,
thalach,
oldpeak,
ca,
target) %>%
gather(key = "key",
value = "value",
-target) %>%
ggplot(aes(y = value)) +
geom_boxplot(aes(fill = target),
alpha = .6,
fatten = .7) +
labs(x = "",
y = "",
title = "Boxplots for Numeric Variables") +
scale_fill_manual(
values = c("#fde725ff", "#20a486ff"),
name = "Heart\nDisease",
labels = c("No HD", "Yes HD")) +
theme(
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
facet_wrap(~ key,
scales = "free",
ncol = 2)
p
推荐阅读
- ios - 在 Xcode 11 中,Live Preview 按钮下方的按钮是什么?
- python - 在没有主目录名称的情况下启动 os.walk
- progress-bar - Inno Setup:如何处理 [UninstallDelete] 部分的进度条?
- sql - 选择包含其他列的列,SQL
- mongodb - 如何在 MongoDB 4.0 上创建副本集
- javascript - 根据选定的单选按钮将两个字段显示为必填字段
- jquery - event.preventDefault(); 无法在 ajax post laravel Framework 5.8.17 中工作
- c# - .NET Core 但不是 .NET Framework 的 400 BadRequest 响应
- javascript - 在下面的所有 div 上使用 css 模糊效果
- beagleboneblack - 在 BeagleBone Black 上读取、加载和卸载驱动程序的命令?