Error with select method to plot box plot using R

Viewed 76

I am working with ggplot to display box plot with multiple variables and I used select method and this error appear so how to resolve this issue

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')"
1 Answers

Based on the code, the heart[,1] implies we are subsetting the first column and if it is a data.frame, it will be coerced to a vector because drop = TRUE by default and thus select cannot be applied on a vector. If df is the dataset object and heart is one of the columns, then we need %>% to connect the two. Similarly, there needs to be connection to 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
Related