1

I want to be able to return group_by summary, table of a variable and geom_boxplot for a dataset

Reproducible example:

set.seed(100)
df <- data.frame(Groups = rep(c("Group1","Group2","Group3"),times = 3), 
                 AGroup = rep(c("GroupA","GroupB","GroupC"), each = 3),
                 Amount = sample(400:500, 9))

Printed output of the data frame

   > df
      Groups AGroup Amount
    1 Group1 GroupA    450
    2 Group2 GroupA    404
    3 Group3 GroupA    474
    4 Group1 GroupB    421
    5 Group2 GroupB    445
    6 Group3 GroupB    439
    7 Group1 GroupC    418
    8 Group2 GroupC    446
    9 Group3 GroupC    448

The function for returning the outputs declared below:

fun1 <- function(var_name) {
  table <- table(df$var_name)
  summary_table <- df %>% group_by_(var_name) %>% summarise(mean(Amount))
  plot <- ggplot(df, aes(var_name, Amount)) + geom_boxplot()
  list(table, summary_table, plot) }

Here is the output of the function

> fun1("Groups")
[[1]]
< table of extent 0 >

[[2]]
# A tibble: 3 × 2
  Groups `mean(Amount)`
  <fctr>          <dbl>
1 Group1       429.6667
2 Group2       431.6667
3 Group3       453.6667

[[3]]

reproducible example

Somewhere I have gone wrong.. I guess.. Please help

Sukumar
  • 41
  • 4
  • 1
    Can you provide a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? – Samuel Mar 27 '17 at 07:10

1 Answers1

1

Actually, I tried this and worked.. Surprising how small things can solve complex problems.. :)

  check2 <- function(var) {
  colindex <- which(colnames(dm1)==var)
  variable <- dm1[,colindex] %>% unlist() %>% as.factor()
  table <- table(dm1[,colindex])
  summarise_amount <- dm1 %>% group_by_(.dots = var) %>% summarise(mean(AmountSpent))
  plot <- ggplot(dm1, aes(x = variable,y = AmountSpent)) + geom_boxplot()
  list(table, summarise_amount, plot)
}

This is the output:

> with(dm1, check2("OwnHome"))
[[1]]

 Own Rent 
 516  484 

[[2]]
# A tibble: 2 × 2
  OwnHome `mean(AmountSpent)`
   <fctr>               <dbl>
1     Own           1543.1357
2    Rent            868.8264

[[3]]

Boxplot

Sukumar
  • 41
  • 4