首页 > 解决方案 > 使用 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')"

标签: rggplot2dplyrboxplot

解决方案


根据代码,这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

推荐阅读