Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple outputs from single menu

Tags:

r

menu

Suppose I have a data frame like this:

Class  Sex  Score
A      M    90
A      F    90
A      F    85
A      M    85
A      M    80
A      M    70
A      F    70
A      M    60
B      F    90
B      M    90
B      M    75
B      F    70

and I want a single menu that selects the class and the sex and gets the average. Right now on my real data frame I'm using two menus

i <- menu(c("A","B"), graphics=TRUE, title="Choose class")
j <- menu(c("M","F"), graphics=TRUE, title="Choose sex")
df.1 <- df.1[df.1$Class==i, ]
df.1 <- df.1[df.1$Sex==j, ]

But when there are many more variables than just Class and Sex it seems annoying to click multiple menus when they could all be selected in the one window. Is this possible in R?

like image 697
Hugh Avatar asked Mar 20 '26 11:03

Hugh


1 Answers

This could be modified but the basic idea is to create an intersection of all of your options that show up and just use a single menu.

dat <- read.table(textConnection("Class  Sex  Score
A      M    90
A      F    90
A      F    85
A      M    85
A      M    80
A      M    70
A      F    70
A      M    60
B      F    90
B      M    90
B      M    75
B      F    70
"), header = TRUE)

vals <- interaction(dat$Class, dat$Sex)
opts <- as.character(unique(vals))
choice <- menu(opts, graphics = TRUE, title = "Choose Class.Sex")
dat[vals == opts[choice],]

and here is that idea wrapped up into a function

# data - dataset to subset
# cols - either character vector with names of the columns
#        or numeric vector with column numbers
# graphics - logical. Should the menu be graphical?
subsetMenu <- function(data, cols, graphics = TRUE){
    if(is.numeric(cols)){
        colnames <- colnames(data)[cols]
    }else{
        colnames <- cols
    }

    vals <- interaction(data[,cols])
    opts <- as.character(unique(vals))
    title <- paste("Choose", paste0(colnames, collapse = "."))

    choice <- menu(opts, graphics = graphics, title = title)
    data[vals == opts[choice],]
}

df1 <- subsetMenu(dat, c("Class", "Sex"), graphics = T)
df2 <- subsetMenu(dat, c("Class", "Sex"), graphics = F)
df3 <- subsetMenu(dat, 1:2)
df4 <- subsetMetu(mtcars, c("cyl", "gear"))
like image 52
Dason Avatar answered Mar 22 '26 03:03

Dason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!