假设我有一个像这样的数据框:
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
我想要一个菜单来选择班级和性别,并获取平均值。现在在我的真实数据框上,我正在使用两个菜单
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, ]
但是,当变量多于
Class
和Sex
时,如果可以在一个窗口中选择多个菜单,则单击多个菜单似乎很烦人。在R
中可以吗? 最佳答案
可以对此进行修改,但是基本思想是创建所有显示的选项的交叉点,并且仅使用一个菜单即可。
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],]
这就是将这个想法包装成一个函数
# 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"))